Jump to content

preg_match to get some strings from an array


etrader

Recommended Posts

I want to select some strings from an array (list of urls) with this code

$pattern = "/books/";
if(preg_match($pattern, $list)) {

 

I have two questions:

 

1. When I put "/5" as the pattern (I mean having a term in the url starting with 5), I get this error: Warning: preg_match() [function.preg-match]: No ending delimiter '/' found

 

2. What if I want to add two if conditions? I mean if the string contains "/books/" and "/5" ?

 

;D

 

Okay so first off, you are getting the error because a regex pattern is supposed to be wrapped in a delimiter. When you do "/books/" you are expecting to match for "/books/" but what is really happening is preg_match() is using the / as the delimiter and matching for "books".  But with "/5" it's trying to take the / as the delimiter and you don't have the matching ending delimiter.

 

You can use most any non-alphanumeric character as the delimiter, such as the / as I have just told you.  But since you are working with URLs, I suggest you pick a delimiter that isn't /.  So for $pattern, if you want to match for "/books/", $pattern should really be for example "~/books/~" and ~ is the delimiter.  Same with "/5" : use "~/5~"

 

2nd thing.  If you are just looking for exact strings within a string instead of patterns, you shouldn't be using regex, as it is less efficient.  For instance there is no pattern in "/books/" it's a static string.  Regex is for matching something that follows a pattern.  Instead, use something like stripos() to check if the string exists in the URL (and with stripos() you don't use delimiters)

 

Here is an example of what you should be doing:

 

function find_urls ($list,$patterns) {
  if (!is_array($list)) $list = array($list);
  if (!is_array($patterns)) $patterns = array($patterns);
  $matches = array();
  foreach ($list as $url) {
    foreach ($patterns as $pattern) {
      if (stripos($url,$pattern) !== false) $matches[] = $url;
    }
  }
  return $matches;
}

 

example

// array of URLs
$list = array('http://www.somesite.com/books/blah','url','blah.com/5','url','url');

// array of all the patterns you want to match
$patterns = array('/books/','/5');

// get matching urls
$matched_urls = find_urls($list,$patterns);

// output
echo "<pre>";
print_r($matched_urls);

 

output

Array
(
    [0] => http://www.somesite.com/books/blah
    [1] => blah.com/5

)

 

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.