Is there a PHP function that can escape regex patterns before they are applied?

Viewed 53031

Is there a PHP function that can escape regex patterns before they are applied?

I am looking for something along the lines of the C# Regex.Escape() function.

2 Answers

It would be much safer to use Prepared Patterns from T-Regx:

$url = 'http://stackoverflow.com/questions?sort=newest';

$pattern = Pattern::inject('\s@\s', [$url]);
                                    // ↑ $url is quoted

then perform normal match:

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";

$matcher = pattern->match($haystack);
$matches = $match->all();

you can even use it with preg_match():

preg_match($pattern, 'foo', $matches);
Related