I have the following code:
//Array filled with data from external file
$patterns = array('!test!', 'stuff1', 'all!!', '');
//Delete empty values in array
$patterns = array_filter($patterns);
foreach($patterns as &$item){
$item = preg_quote($item);
}
$pattern = '/(\b|^|- |--|-)(?:'.implode('|', $patterns).')(-|--| -|\b|$)/i';
$clid = "I am the !test! stuff1 all!! string";
echo $clid;
$clid = trim(preg_replace($pattern, ' ', $clid));
echo $clid;
Output:
//I am the !test! stuff1 all!! string
//I am the !test! all!! string
I'm escaping the !
with preg_quote
, so why?
I had a second problem, which is now solved, but I don't know why it happened.
Suppose $clid = "I am Jörg Müller with special chars"
. If I remove the code line $patterns = array_filter($patterns);
then the output after preg_replace
was I am J
. I cannot find out why, but I solved the problem with array_filter
.
Thank you