Tim Tim - 1 month ago 15
PHP Question

PHP 5.5 preg_replace using array of patterns returning null

I've looked at other questions on this similar topic, and tried those suggestions but they don't seem to work.

This is my code:

<?php

$badChars = array('/</', '/>/', '/$/', '/\\/', '/=/', '/@/', '/\//');

$cleanData = "Text -with /stuff I don@'t want";

echo $cleanData . "\n";

$cleanData = preg_replace($badChars, '', $cleanData);

echo $cleanData . "\n";

?>


Note that the array of patterns will vary based on the scenario. This is for a data cleansing exercise. e.g.: if processing an email field, we'd temporarily drop the @ pattern.

And this is the output:

Text -with /stuff I don@'t want

PHP Warning: preg_replace(): No ending delimiter '/' found in /home/tim/xm_code/symphony/code/components/controllers/test.php on line 9

Process finished with exit code 0


I can't find anything to help me resolve this. Any ideas?

Answer

Your double backslash is escaping your closing delimiter. So

'/\\/'

needs to be

'/\\\/'

Alternatively use a character class and you don't need the array. Second alternative, use str_replace since the characters are all static.

$badChars = array('<', '>', '$', '\\', '=', '@', '/');
$cleanData = "Text -with /stuff I don@'t want";
echo $cleanData . "\n";
$cleanData = str_replace($badChars, '', $cleanData);