peter
peter

Reputation: 4411

Make string replacements using an associative array

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?

Upvotes: 11

Views: 13900

Answers (3)

Amal Murali
Amal Murali

Reputation: 76656

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.

Upvotes: 19

John Conde
John Conde

Reputation: 219814

Off of the top of my head:

$find       = array_keys($list);
$replace    = array_values($list);
$new_string = str_ireplace($find, $replace, $string);

Upvotes: 24

srain
srain

Reputation: 9082

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);

Upvotes: 1

Related Questions