Quote regular expression

Dedicated builder

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:

Procedural Quoting

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 version, and Pattern::quote() fixes it)...

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.

Contract

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