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.
Author by
Dranzer
Updated on June 04, 2022Comments
-
Dranzer almost 2 years
I want to replace multiple characters in a string with other characters i.e. say
<
toa
,>
tob
,!
toc
,$
tod
, etc. I want to achieve this goal by usingpreg_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?