Replacing deprecated ereg_replace() with preg_repl

2019-08-13 00:37发布

问题:

The following PHP program replaces the symbols !£$%^& with nulls

 <?php

 $string = "This is some text and numbers 12345 and symbols !£$%^&";
 $new_string = ereg_replace("[^A-Za-z0-9 (),.]", "", $string);
 echo "Old string is: ".$string."<br />New string is: ".$new_string;

 ?>

Output:

Old string is: This is some text and numbers 12345 and symbols !£$%^&
New string is: This is some text and numbers 12345 and symbols

But, I have learned that the function ereg_replace() has been deprecated and that I should use the function preg_replace() instead. I made the substitution like so:

 <?php

 $string = "This is some text and numbers 12345 and symbols !£$%^&";
 $new_string = preg_replace("[^A-Za-z0-9 (),.]", "", $string);
 echo "Old string is: ".$string."<br />New string is: ".$new_string;

 ?>

but got the wrong output:

Old string is: This is some text and numbers 12345 and symbols !£$%^& New string is: This is some text and numbers 12345 and symbols !£$%^&

What did I do wrong? How do I fix it?

回答1:

You seem to be missing markers around the regular expression. Try this instead (note the slashes around the pattern).

$string = "This is some text and numbers 12345 and symbols !$%^&";
$new_string = preg_replace("/[^A-Za-z0-9 (),.]/", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;

You can use any character for the markers as long as the same one is found on both sides. Very useful if your pattern is matching / characters. So this is also valid:

$string = "This is some text and numbers 12345 and symbols !$%^&";
$new_string = preg_replace("~[^A-Za-z0-9 (),.]~", "", $string);
echo "Old string is: ".$string."<br />New string is: ".$new_string;


回答2:

This is a weird bug that I have experienced as well. for some reason the empty quotes screw up this function but I got it to work by using

preg_replace($pattern, NULL, $string);

instead of

preg_replace($pattern, "", $string);