Pawka
Pawka

Reputation: 2576

Replace words or words combinations with PHP regexp

I have map for replacement words:

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

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

I could split string with regexp to words but this does not work when there will be mapped values with few tokens (like word2 blah).

Upvotes: 4

Views: 655

Answers (1)

codaddict
codaddict

Reputation: 454940

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

See it

Upvotes: 5

Related Questions