0

I am trying to preg_match by using preg_quote for my pattern and subject. Problem is that preg_match doesn't seem to match them.

I removed the preg_quote and it matched me just fine. I preg_quote subject and message to see what it's the output and they are exactly the same but preg_match doesn't seem to match them. I need to have the preg_quote for some cases.

$message = "My two great things in life are spaghetti and bolognese Order yours #online from Ammou Pizza in Limassol!

foody.com.cy/ammou-pizza";

if(preg_match('#' . preg_quote("ammou-pizza") . '#',  preg_quote($message)))
    echo 'here';

I expect the output to be 'here' but the actual output is just the exit code 0.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Eleni Ioakim
  • 53
  • 1
  • 7
  • It doesn't make a difference in your sample but just to mention, it's important to also specify the delimiter when using preg_quote: `'#'.preg_quote("blafoo","#").'#'`... else the regex will break as soon as you have an `#` in your search substring. – bobble bubble Jun 08 '19 at 10:52

2 Answers2

1

You shouldn't use preg_quote($message) for your original text in the subject to search . This is ONLY to make sure any text is a valid regex expression. If you echo out the result of this you get...

My two great things in life are spaghetti and bolognese Order yours #online from Ammou Pizza in Limassol\!

foody\.com\.cy/ammou\-pizza

and as you can see it has encoded ammou\-pizza. This isn't what you want, the \- sequence is only needed as - is means something different to regex other than a simple dash.

Just use...

if(preg_match('#' . preg_quote("ammou-pizza") . '#',  $message))
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

preg_quote is useless here because you have no special character in your regex, use:

if ( preg_match('#ammou-pizza#', $message) )
    echo 'here';

In your case, the use of preg_match is not mandatory, uou'd better use [strstr][1], it is much more efficient as you want to find a simple string:

if (strstr('ammou-pizza', $message) )
    echo 'here';
Toto
  • 89,455
  • 62
  • 89
  • 125
  • @NigelRen: You're probably right, but I've answered for this specific question. Let's OP decide what they really want. I agree that your answer is much more generic. – Toto Jun 08 '19 at 11:58
  • @NigelRen indeed answered my question. – Eleni Ioakim Jun 08 '19 at 18:13