user1107199
user1107199

Reputation: 589

Replacing deprecated ereg_replace() with preg_replace() did not work

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?

Upvotes: 1

Views: 8100

Answers (2)

MightyE
MightyE

Reputation: 2679

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;

Upvotes: 4

Decker Brower
Decker Brower

Reputation: 1

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

Upvotes: -2

Related Questions