defvayne23 Posted March 2, 2008 Share Posted March 2, 2008 I'm wanting to match an array of patterns to a string and return the first match. Problem is preg_match only accepts a string for a pattern and not mixed. My thought was to loop through the array and match to the string, problem bieng is it will be used on every page call with the string as the url (I'm using mod_rewrite) to figure out what information to display. If anyone has used Django which is a python framework, it would work just like its url system. http://www.djangoproject.com/documentation/url_dispatch/ Does anyone see the loop as an issue on a moderate visited site, or have a more efficient way of doing it? Quote Link to comment Share on other sites More sharing options...
trq Posted March 2, 2008 Share Posted March 2, 2008 Does anyone see the loop as an issue on a moderate visited site, or have a more efficient way of doing it? I don't see it as an issue at all. Many php frameworks would use a similar procedure for there router (I know mine does, without issue). Quote Link to comment Share on other sites More sharing options...
dsaba Posted March 2, 2008 Share Posted March 2, 2008 you can combine all the patterns into 1 pattern that will match them all, ie: <?php $patArr['patOne'] = '\d{3}literal\d{5}'; $patArr['patTwo'] = '(?<!string literal)other literal'; $bigPat = '~(?:'; foreach ($patArr as $k => $pat) { $bigPat .= '(?P<'.$k.'>'.$pat.')|'; } $bigPat = substr($bigPat, 0, strlen($bigPat)-2); $bigPat .= ')~i'; ?> Quote Link to comment Share on other sites More sharing options...
defvayne23 Posted March 3, 2008 Author Share Posted March 3, 2008 I now understand the use of the | on multiple patterns. But I am very confused on how alot of stuff you have in your code works. Did a test with: <?php $array = Array( "/pages/[0-9]+/", "/test/" ); preg_match("/".str_replace("/","\/",implode("|",$array))."/", "/pages/5/", $matches); echo "<pre>"; print_r($matches); echo "</pre>"; ?> Quote Link to comment Share on other sites More sharing options...
dsaba Posted March 4, 2008 Share Posted March 4, 2008 instead of using str_replace() to escape the / slashes in the patterns you can use http://php.net/preg_quote All I am doing really is matching each of the patterns in the array as subgroups in the combined pattern. Normally preg_match_all() returns subgroups with numerical keys in the order that they are matched, this syntax (?P<customsubgroupKey>) returns a custom subgroup key, so you can access your subgroup matches in preg_match_all() with more ease/organization. If its the regex syntax that is confusing you, look it up. Quote Link to comment Share on other sites More sharing options...
defvayne23 Posted March 4, 2008 Author Share Posted March 4, 2008 Cool, thanks for the help Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.