How to replace multiple characters with corresponding multiple characters in php?

10,689

Solution 1

why want you to use a regex to achieve this? just use str_replace, which is a lot faster.

$replace = str_replace(array('<', '>', '!'), array('a', 'b', 'c'), $text);

Solution 2

You may use simple replace, in your case regex will be an overkill. For example:

$result = strtr($data, [
  '<' => 'a',
  '>' => 'b',
  '!' => 'c',
  //e t.c.
]);

Alternative would be str_replace(), but I think associative array looks more readable.

Share:
10,689
Dranzer
Author by

Dranzer

Updated on June 04, 2022

Comments

  • Dranzer
    Dranzer almost 2 years

    I want to replace multiple characters in a string with other characters i.e. say < to a, > to b, ! to c, $ to d, etc. I want to achieve this goal by using preg_replace in PHP. Can I do this in just one line of code or should I go for breaking the string , making an array and then replace it?