Correct rules for escaping special characters in a preg_match()

I am trying to learn how to use preg_match() and already I am having problems understanding the logic. At the moment I am exploring searching for special characters using escapes.

I have established that the special characters that need escaping are . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

All good so far as in if (preg_match("/\?/", $string)) {...

But if I search for a \ then I need to escape it with a \\as in if (preg_match("/\\\/", $string)) {...

Ok, I can accept that as a special case but if I want to search for a double backslash \\ as in if (preg_match("/\\\\/", $string)){...

This works but it also returns true for a single backslash found in the string

If I try escaping both backslashes with a double backslash if (preg_match("/\\\\\\/", $string)){... then I get an error No ending delimiter '/' found

I am having trouble understanding the rules or logic behind when and where to escape with a \ when using preg_match()

This should help - https://www.php.net/manual/en/function.preg-quote.php

1 Like

Yes THANKS that will help a lot. Any chance that you or someone could explain this section on that page though please.

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

And is there a really good BASIC introduction to learning preg_match() from scratch

Thanks again !

If the pattern being searched for contains the delimiter / characters, such as if you were matching part of a url or a file system path, supplying the delimiter as the 2nd parameter will cause the / characters in the pattern to be escaped, distinguishing them form the actual / delimiters.

1 Like
$x = "/this pattern cant match http://www.example.com because the pattern ended back at the first slash after the colon./"
$y = "/".preg_quote("this pattern will match http://www.example.com because the inline delimiters get escaped.",'/')."/";
$z = "/I could also do it myself. http:\/\/www.example.com./"
$r = "~or just use a different http://www.example.com delimiter altogether... \( / is not normally a special character. But these parenthesis are. \)~";
1 Like

Thank you

Thanks