How to Replace Words in a String Based on a Map in PHP?

Let's suppose we have the following map of key/value pairs where the keys represent the words to be replaced and values represent the replacements for their respective keys:

$langMap = [
    'js' => 'JavaScript',
    'py' => 'Python',

To replace words in a string based on our map we can use str_replace() like so:

$str = 'I love working with js, py and PHP.';

echo str_replace(array_keys($langMap), $langMap, $str);

// output: 'I love working with JavaScript, Python and PHP.'

In the example above you can see that the keys in our map are searched for in the string and replaced with their corresponding values. This works because str_replace() can take an array as an argument for words to search for (i.e. the first argument) and also for the words to replace with (i.e. the second argument).

Hope you found this post useful. It was published . Please show your love and support by sharing this post.