Regex does not render well using PHP preg_quote

Hi I am trying to concatenate a string before converting that string to a regex in PHP, but the problem is that it is not displayed as expected. I searched using google and found out about preg_quote , the problem is it doesn't work well.

Here's my example:

$mystring = "banana"; // put this to a variable assume this value is dynamic
$regex_str = "/^"$mystring"\-[a-z0-9]\-[a-z0-9]$/"; 
//Im expecting expecting /^banana\-[a-z0-9]\-[a-z0-9]$/
$regex = preg_quote($regex_str);

      

but i get:

/\^banana\\\-\[a\-z0\-9\]\\\-\[a\-z0\-9\]\$/

      

and always returns the wrong value.

+3


source to share


1 answer


Call preg_quote()

on the string you add, before adding it to the regex:



$mystring = "banana";
$regex_str = "/^" . preg_quote($mystring, "/") . "\-[a-z0-9]\-[a-z0-9]$/"; 

      

+4


source







All Articles