Last Updated: February 25, 2016
· alixaxel

Avoid Escaping PCRE Patterns

The default PCRE delimiter / is too common in many strings related to usual web development, be it a protocol scheme, a full URI or a path component, so instead of having to escape stuff like this (PHP):

preg_match('/https:\/\/coderwall\.com\/p\/new/', $url);

You could just save yourself the hassle and use another uncommon, yet valid delimiter (like §, or my favorite ~):

preg_match('~https://coderwall\.com/p/new~', $url);

I've been this convention it for years and I don't know how I could have ever used any other delimiter. One uncommon, yet important caveat - if your pattern is supplied by the user, or if you just want to escape it using the PCRE functions, you need to pass the delimiter you chose as well:

// returns https://coderwall\.com/p/new
preg_quote('', '~');

That's it! I hope this saves you lots of seconds during your regexing.