Mansoor Jafar
Mansoor Jafar

Reputation: 1488

replace different sub strings in a string

I want to replace different sub-strings with multiple different strings in a string, is there a nicer way to do rather than i do labor work and use

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

as many times as the number of strings to be replaced?

for example: replace a, b and c with d, e and f respectively in any sample string. Of course i have a large number of words to change for this i need it.

Upvotes: 0

Views: 148

Answers (2)

LSerni
LSerni

Reputation: 57388

The usual way of doing this is to supply an array of translations

$xlat = array(
    'a' => 'd',
    'b' => 'e',
    'c' => 'f',
);

and then pass it to str_replace:

$result = str_replace(array_keys($xlat), array_values($xlat), $source);

You can build the array from a SQL query or other source.

You must be careful in case there is an intersection between the source and replacement string sets, or internal matches between source strings, e.g.

  'Alpha'  => 'Beta',
  'Beta'   => 'Gamma',

or even more sneaky,

  'Alpha'    => 'Beta',
  'Alphabet' => 'ABCDEFGHIJ',

because internally str_replace employs a loop, and therefore "Base Alpha" would come out as "Base Gamma", and "Alphabet" as "Betabet" instead of "ABCDEFGHIJ". One possible way of coping with this is build $xlat incrementally; if you find that in the new couple 'a' => 'b', 'a' is already in the values of $xlat, you can push it onto $xlat instead of appending. Of course, more complicated sets of keywords (or even the exchange of two or more terms) might not be solvable.

Another way is to do it in two runs: you first generate a $xlat1 array of the form

 'a' => '###<UNIQUEID1>###',
 'b' => '###<UNIQUEID2>###',

and a second array of the form

 '###<UNIQUEID1>###' => 'c',
 '###<UNIQUEID2>###' => 'd',

You may "upgrade" the first one-array form to the second with a loop:

 // First step, we sort $xlat in order of decreasing key size.
 // This ensures that *Alphabet* will be replaced before *Alpha* is ever checked.

 // Then we build
 foreach($xlat as $from => $to)
 {
     $id = uniqid();
     $xlat1[$from] = $id;
     $xlat2[$id]   = $to;
 }
 $temp = str_replace(array_keys($xlat1), array_values($xlat1), $source);
 $result = str_replace(array_keys($xlat2), array_values($xlat2), $temp);

Upvotes: 0

str_replace() accepts an array for both search and replace parameters, so you can pass several strings in array to search and will be replaced by the corresponding strings in the array passed in replace parameter, like so:

$search = array('a','b','c');
$replace = array('d','e','f');

$res = str_replace($search, $replace, 'a b cool');
echo $res; //echoes 'd e fool'

Upvotes: 6

Related Questions