phpregexescapingpreg-match

is there a function to escape special characters in a regex string?


I am trying to match some link from some texts:

$reg = '#ok is it http://google.com/?s=us#';
$page = 'Well i think ! ok is it http://google.com/?s=us&ui=pl0 anyways it ok';

if (preg_match($reg,$page)) {
  echo 'it work'; 
} else {
  echo 'not work';
}

If I use $reg = '#ok is it http://google.com/'; then it's okay, but when I use that pattern with "?=" it doesn't match.

I understand there is some problem of a syntax error. Is there any function or ready made function which automatically escape these special characters?


Solution

  • You have a lot of syntax errors. You must escape all the special chars as '.', '?' and so on. Thus you have to replace the chars like this:

    '.' -> '\.'
    '?' -> '\?'
    ...
    

    Anyway, the regex should be like this:

    $reg = '#ok is it http:\/\/google\.com/\?s=us#';