Question

for an url routing I have

Patern :

/^\/stuff\/other-stuff\/(?:([^\/]\+?))$/i

Subject :

/stuff/other-stuff/foo-AB123456.html

why $num_matches is equal to 0 ??

$num_matches = preg_match_all($patern, $subject, $matches);

Help should be greatly appreciated :)

Was it helpful?

Solution

because of this:

[^\/]\+?

firstly there is no slash after other-stuff so you cannot find the sentence with a negated / secondly the + must not be escaped if you are doing this kind of match . + must only be escaped when you are doing a literal match.

the corrected regex should be :

^\/stuff\/other-stuff\/(?:(.+?))$

demo here : http://regex101.com/r/aV9cR0

will match foo-AB123456.html in the first capture

OTHER TIPS

$patern= "#^/stuff/other-stuff/([^/]+)$#i";


$subject = "/stuff/other-stuff/foo-AB123456.html";


preg_match_all($patern, $subject, $matches);

print_r($matches[1]);

It looks to me like your regex could be simplified to something like:

(?i)^/stuff/other-stuff/[\w-.]+$

It would work like this:

<?php
$regex="~(?i)^/stuff/other-stuff/([\w-./]+)$~";
$string = "/stuff/other-stuff/foo-AB123456.html";
$hit = preg_match($regex,$string,$m);
echo $m[0]."<br />";
echo $m[1]."<br />";
?>

Output:

/stuff/other-stuff/foo-AB123456.html
foo-AB123456.html

Note that this could be done in a number of different ways.

Here are some details about the regex.

  1. The ~ delimiter is nicer than the original / because you don't have to escape the slashes.
  2. The parentheses in ([\w-.]+) capture the end of the url into Group 1. This is why $m[1] yields foo-AB123456.html
  3. After the final slash, [\w-./]+ matches any number of letters or digits, underscores, dashes, dots and forward slashes. This is a "mini-spec" for what characters we expect there. If you want to allow anything at all, you could go with a simple dot.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top