Is there a PHP function that can escape regex patterns before they are applied? -
is there php function can escape regex patterns before applied?
i looking along lines of c# regex.escape()
function.
preg_quote()
looking for:
description
string preg_quote ( string $str [, string $delimiter = null ] )
preg_quote() takes
str
, puts backslash in front of every character part of regular expression syntax. useful if have run-time string need match in text , string may contain special regex characters.the special regular expression characters are:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
parameters
str
the input string.
delimiter
if optional delimiter specified, escaped. useful escaping delimiter required pcre functions. / commonly used delimiter.
importantly, note if $delimiter
argument not specified, delimiter - character used enclose regex, commonly forward slash (/
) - not escaped. want pass whatever delimiter using regex $delimiter
argument.
example - using preg_match
find occurrences of given url surrounded whitespace:
$url = 'http://stackoverflow.com/questions?sort=newest'; // preg_quote escapes dot, question mark , equals sign in url (by // default) forward slashes (because pass '/' // $delimiter argument). $escapedurl = preg_quote($url, '/'); // enclose our regex in '/' characters here - same delimiter passed // preg_quote $regex = '/\s' . $escapedurl . '\s/'; // $regex now: /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/ $haystack = "bla bla http://stackoverflow.com/questions?sort=newest bla bla"; preg_match($regex, $haystack, $matches); var_dump($matches); // array(1) { // [0]=> // string(48) " http://stackoverflow.com/questions?sort=newest " // }
Comments
Post a Comment