2

Hi Im trying to concatinate a string before converting that string into regex in PHP, but the problem is it's not displaying as expected. I've been searching using google and found out about preg_quote, problem is it's not working well.

Here is 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 what I am getting is:

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

and always returning the wrong value.

loki9
  • 625
  • 7
  • 20
  • 3
    `preg_quote()` is intended to be called on the string you're adding into the regex, not on the entire regex after the addition. – Amber Jun 08 '15 at 02:39
  • You quote `$mystring` and concatenate it with the rest of the regex. There is no meaning in quoting the whole regex. – nhahtdh Jun 08 '15 at 02:40
  • Is that your actual code? You should be getting an error. – Anonymous Jun 08 '15 at 02:41
  • @Anonymous yeah I know right? that's why I'm asking on how to fix this. thanks – loki9 Jun 08 '15 at 02:42
  • @loki9 No, I mean the code you show doesn't even produce an output besides the syntax error. The code you're actually using is likely different. – Anonymous Jun 08 '15 at 02:43
  • actually it wont display an syntax error because I just echoed it. – loki9 Jun 08 '15 at 02:44
  • @loki9 Try testing exactly the code you used in the question. You should see a syntax error from PHP on the second line. – Anonymous Jun 08 '15 at 02:49

1 Answers1

4

Call preg_quote() on the string you're adding before you add it into the regex:

$mystring = "banana";
$regex_str = "/^" . preg_quote($mystring, "/") . "\-[a-z0-9]\-[a-z0-9]$/"; 
Amber
  • 507,862
  • 82
  • 626
  • 550