How replace replace all specific characters using PHP ereg_replace?

514 Views Asked by At

I want replace specific symbols with sign % using regular expressions on PHP. E.g.

$result = ereg_replace('xlp','%','example')`. //$result = `'e%a%%me'

It is possible or I should use other way?

2

There are 2 best solutions below

0
hjpotter92 On BEST ANSWER

First and foremost, about ereg_replace:

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Use preg_replace instead.

Next, in your pattern, you are searching for the literal string xlp. Put them in a character-set to match one of the three.

$result = preg_replace(
    "/[xlp]/",
    "%",
    $string
);
1
Alex Andrei On

preg_replace is good, but let's not forget about str_replace

print str_replace(array('x','l','p'),array('%','%','%'),'example');
// or
print str_replace(array('x','l','p'),'%','example');

//will output
e%am%%e