I’m trying to extract three parts with a regular expression. It works for the controller and the id but not for the slug, I can not remove the last -
<?php
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z] )\/(?<slug>[a-z0-9\-] )(?<=\-)(?<id>[0-9] )/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value){
if(!is_numeric($key)){
$routes[$key] = $value;
}
}
var_dump($routes);
I get the following result :
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(20) "my-second-article-2-"
["id"]=>
string(3) "155"
}
But i want this slug :
["slug"]=>
string(20) "my-second-article-2"
Thanks
CodePudding user response:
You may use the following regex pattern:
/(?<controller>[a-z] )\/(?<slug>[a-z0-9] (?:-[a-z0-9] ) )-(?<id>[0-9] )/i
Your updated PHP script:
$url = "/cockpit/posts/my-second-article-2-155";
$routes = [];
$patterns = "/(?<controller>[a-z] )\/(?<slug>[a-z0-9] (?:-[a-z0-9] ) )-(?<id>[0-9] )/i";
preg_match($patterns, $url, $matches);
foreach ($matches as $key => $value) {
if (!is_numeric($key)) {
$routes[$key] = $value;
}
}
var_dump($routes);
This prints:
array(3) {
["controller"]=>
string(5) "posts"
["slug"]=>
string(19) "my-second-article-2"
["id"]=>
string(3) "155"
}
The final portion of the updated regex says to match:
[a-z0-9]
alphanumeric term(?:-[a-z0-9] )
followed by hyphen and another alphanumeric term, both 1 or more times-
match a literal hyphen[0-9]
match the id