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::prepare(["(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::prepare(), Pattern::inject() and Pattern::bind().

Procedural quoting - be careful

There are two methods Pattern::quote() and Pattern::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).

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

...second of which is the direct opposite:

Pattern::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 = Pattern::unquote(Pattern::quote($input));
// then
$this->assertEquals($input, $output);

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

Last updated on