Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple characters with corresponding multiple characters in php? [closed]

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?

like image 579
Dranzer Avatar asked Jan 23 '14 13:01

Dranzer


2 Answers

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);
like image 76
Philipp Avatar answered Sep 24 '22 01:09

Philipp


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.

like image 44
Alma Do Avatar answered Sep 27 '22 01:09

Alma Do