2

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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Edgaras Karka
  • 7,400
  • 15
  • 61
  • 115

2 Answers2

3

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
);
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
3

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
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42