Replace words or word combinations with PHP regexp

I have a map for substitute words:

$map = array( 'word1' => 'replacement1', 'word2 blah' => 'replacement 2', //... ); 

I need to replace the words in a string. But replacement should only be done when the string is a word:

  • It is not in the middle of any other ex word. textword1 will not be replaced by replacement1, as it is part of another token.
  • Separators should be retained, but the words before / after them should be replaced.

I could split the regular expression string into words, but this does not work when values ​​with multiple tokens will be displayed (e.g. word2 blah).

+4
source share
1 answer
 $map = array( 'foo' => 'FOO', 'over' => 'OVER'); // get the keys. $keys = array_keys($map); // get the values. $values = array_values($map); // surround each key in word boundary and regex delimiter // also escape any regex metachar in the key foreach($keys as &$key) { $key = '/\b'.preg_quote($key).'\b/'; } // input string. $str = 'Hi foo over the foobar in stackoverflow'; // do the replacement using preg_replace $str = preg_replace($keys,$values,$str); 

Take a look

+5
source

Source: https://habr.com/ru/post/1382444/


All Articles