Jump to content

Help with preg_match_all('!/search/(.*)/([0-9])!i', $page, $pages);


jamesmiller

Recommended Posts

Regular expressions have "modifiers" that alter the number of items a specific block can match.  Putting a plus after something means "one or more times."  So if you did [0-9]+ that would match any number of characters.

 

Regular expressions also have built in character classes.  \d means "any digit," so you can replace [0-9]+ with \d+ and get the same results, plus many people think it's more readable.

 

-Dan

Ok new problem its outputting:

 

Array ( [0] => Array ( [0] => href="/search/reg/2/">2 3 4 5 ... 32 Array ( [0] => reg/2/">2 3 4 5 ... 32< ) [2] => Array ( [0] => d ) )

 

The thing is i want /search/reg/number/  to appear in different array places so /search/reg/3/ would be in array value 1 and /search/reg/4/ would be in value 2

The parentheses determine the "capture group."  $matches[0] will be the whole pattern.  $matches[1] will be the first set of parens, $matches[2] will be the second set, etc.

 

What you've posted is too poorly formatted for me to tell what exactly is going on.  Use [ code ] tags around your output so we can see it better.

 

-Dan

This isn't valid output from a print_r statement, there appears to be a great amount of this array missing.

 

Are you using preg_match or preg_match_all?  If you're using preg_match_all then your result will be an array of arrays of matches like I described.

 

Show some more code so we can tell exactly what's up here.  Maybe a little sample app

\d, not d.  Also, your .* is far too greedy, you want something like this:

 function page($page)
{
preg_match_all('!href="/search/(.*?)/(\d+)!i', $page, $pages);
print_r ($pages); 

Once successfully matched, you'll need to loop through $pages to get arrays of matches:

foreach ( $pages as $match ) 
{  
   echo "{$match[1]} .. {$match[2]}<br />\n";
}

-Dan

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.