Which Regular Expression Characters Need Escaping in PHP?

In a PHP regular expression pattern, the following meta-characters (i.e. characters that have a special meaning in a regular expression pattern) must be escaped wherever in the pattern they appear (except within square brackets):

\ ^ $ . [ ] | ( ) ? * + { }

Within square brackets (i.e. []), only the following meta-characters have a special meaning, and they must be escaped:

\ ^ -

You can escape a regular expression meta-character using the general escape character (i.e. \). If you have the need to escape a run-time string that may contain regular expression meta-characters, then you can use the preg_quote() function.

You must remember to also escape the delimiter character if it is being used in the regular expression pattern.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.