Tim
Tim

Reputation: 207

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?

Upvotes: 0

Views: 48

Answers (1)

chris85
chris85

Reputation: 23880

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);

Upvotes: 1

Related Questions