0

I want to check if the current $uri_string matches any of these patterns

$uri_string = 'project/details/1258';

$uri_patterns = [
   'project/foo/',
    'project/bizz/',
];


foreach($uri_patterns as $pattern) {
    if(preg_match('/' . $pattern. '/i', $uri_string) == 1) {
        echo 'Is a match!';
    }
}

so if at some point the $uri_string = 'project/foo/123/some-other-params'; then this sould match the 'project/foo/' pattern. How can I do this?

ltdev
  • 4,037
  • 20
  • 69
  • 129

2 Answers2

3

You need to escape the / slashes from your regex like:

$uri_string = 'project/details/1258';

$uri_patterns = [
   'project/foo/',
    'project/bizz/',
];


foreach($uri_patterns as $pattern) {
    $pattern = preg_quote($pattern, '/');
    if(preg_match("/$pattern/i", $uri_string) == 1) {
        echo 'Is a match!';
    }
}

This uses preg_quote() to escape the slashes.

Alternatively, you can use different delimiter for the regex, like #:

 preg_match("#$pattern#i", $uri_string);

Or you can ignore regex completely and use string parsing functions like:

foreach($uri_patterns as $pattern) {
    if(strpos($uri_string, $pattern) !== false) {
        echo 'Is a match!';
    }
} 
mega6382
  • 9,211
  • 17
  • 48
  • 69
2

I think you'll need to escape those forward slashes:

$uri_patterns = [
    'project\/foo\/',
    'project\/bizz\/',
];

Then for your match, use:

preg_match('/' . $pattern . '/i', $uri_string, $matches);
if (!empty($matches)) {
    echo 'Is a match!';
}
OK sure
  • 2,617
  • 16
  • 29