Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php replace all occurances of key from array in string

Tags:

replace

php

maybe this is duplicate but i did't find good solution.

I have array

$list = Array
(
   [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 it with smart way? Many thanks.

like image 900
peter Avatar asked Nov 21 '13 16:11

peter


People also ask

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

What is Array_keys () used for in PHP?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

How do you change the key of an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.


1 Answers

Off of the top of my head:

$find       = array_keys($list);
$replace    = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
like image 106
John Conde Avatar answered Oct 19 '22 10:10

John Conde