A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure):
<?php
function replace_words($list, $line, $callback) {
return preg_replace_callback(
'/(^|[^\\w\\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\\w\\-])/mi',
function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; },
$line
);
}
?>
Example of usage:
<?php
$list = array('php', 'apache web server');
$str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too.";
echo replace_words($list, $str, function($v) {
return "<strong>{$v}</strong>";
});
?>