11

I have an associative array where keys are search strings and values are replacement strings.

$list = ['hi' => 0, 'man' => 1];
$string = "hi man, how are you? man is here. hi again."

It should produce:

$final_string = "0 1, how are you? 1 is here. 0 again."

How can I achieve this?

1
  • 1
    $newString = str_replace(array_keys($list), array_values($list), $string); or $newString = strtr($string, $list); Commented Nov 21, 2013 at 16:21

3 Answers 3

24

Off of the top of my head:

$find       = array_keys($list);
$replace    = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
Sign up to request clarification or add additional context in comments.

3 Comments

@MD.SahibBinMahboob, but it does not work and still some mistake, $keys should be $replace.
@srain You made a good point about case sensitivity. But that is easily remedied by using the case insensitive version of str_replace(), str_ireplace()
$replace = array_values($list); call to array_values is not necessary, you can just pass the $list array to str_replace.
19

Can be done in one line using strtr().

Quoting the documentation:

If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

To get the modified string, you'd just do:

$newString = strtr($string, $list);

This would output:

0 1, how are you? 1 is here. 0 again.

Demo.

2 Comments

Why is this not the accepted answer? This function is designed to do exactly what the OP (and I) is looking for.
@scipilot: It's The Fastest Gun in the West problem :)
1

preg_replace may be helpful.

<?php
$list = Array
(
    'hi' => 0,
    'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";

$patterns = array();
$replacements = array();

foreach ($list as $k => $v)
{
    $patterns[] = '/' . $k . '/i';  // use i to ignore case
    $replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);

1 Comment

I might be inclined to use array_map() to wrap the keys with delimiters rather than a foreach() loop; but it does handle case sensitivity; and could even be tweaked to handle word boundaries as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.