Skip to main content

Quote regular expression

Before you engage in this article, please visit Handling user input first, if you're interested in using unsafe data in your patterns :)

Pattern::inject("(My|Our) dog's name is @!", [$input]);

Suggested articles:

Building your own patterns can be dangerous and lead to security errors. T-Regx offers a rich variety of dedicated builders including Pattern::inject() and Pattern::template().

Procedural quoting - be careful#

There are two methods preq::quote() and preg::unquote().

First of which works as preg_quote() is supposed to work (except for the fact that preg_quote() is broken before PHP 7.1.3).

preg::quote('Welcome\How are you?');
Welcome\\How are you\?

...second of which is the direct opposite:

preg::unquote('Welcome\\How are you\?');
Welcome\How are you?

Please, keep in mind that this is not a safe way to create patterns with unsafe characters - for that, consider using Prepared Patterns.


These two methods should be transitive, so:

// when
$output = preg::unquote(preg::quote($input));
// then
$this->assertEquals($input, $output);

The contract is that $input should be identical to $output for any string value.

Last updated on