I used preg_quote() to escape some special characters. But in the test below, there is something I can’t understand.
Why ‘date:1111aaa’ doesn’t match ???
<?php $PregArray = ['date:1111aaa', ':222aaa', '@odia tvled']; $array['attract (step-date:1111aaa)'] = 'OK'; $array['type (step-date:222aaa)'] = 'OK'; $array['@odia tvled'] = 'OK'; foreach ($PregArray as $key_1 => $val_1) { echo "n--------------"; foreach ($array as $key_2 => $val_2) { if (preg_match("~$val_1~", preg_quote($key_2))) { echo "nOK => $val_1 - ".preg_quote($key_2); break; } else { echo "nNOK !!! => $val_1 - ".preg_quote($key_2); } } }
http://sandbox.onlinephpfunctions.com/code/9ef36e2b010ac1f4f0eaf08881004892bd0cd9c4
Advertisement
Answer
You’re using preg_quote
in the wrong place, it is intended for escaping characters in the pattern, not the test string (see the manual). Change your code to this and it works fine:
foreach ($PregArray as $key_1 => $val_1) { echo "n--------------"; foreach ($array as $key_2 => $val_2) { if (preg_match('~' . preg_quote($val_1) . '~', $key_2)) { echo "nOK => $val_1 - $key_2"; break; } else { echo "nNOK !!! => $val_1 - $key_2"; } } }
Output:
-------------- OK => date:1111aaa - attract (step-date:1111aaa) -------------- NOK !!! => :222aaa - attract (step-date:1111aaa) OK => :222aaa - type (step-date:222aaa) -------------- NOK !!! => @odia tvled - attract (step-date:1111aaa) NOK !!! => @odia tvled - type (step-date:222aaa) OK => @odia tvled - @odia tvled