views:

268

answers:

2
<?php
  $a="php.net s earch for in the all php.net sites this mirror only function 
      list online documentation bug database Site News Archive All Changelogs 
      just pear.php.net just pecl.php.net just talks.php.net general mailing 
      list developer mailing list documentation mailing list What is PHP? PHP 
      is a widely-used...";
?>

I want to highlight specific words.

For example php, net and func:

php.net s earch for in the all **php**.**net** sites this mirror only **func**tion list online documentation bug database Site News Archive All Changelogs just pear.**php**.**net** just pecl.**php**.**net** just talks.php.net general mailing list developer mailing list documentation mailing list What is **PHP**? **PHP** is a widely-used...

Thanks advance.

+1  A: 

You can do the following:

// your string.
$str = "...............";

// list of keywords that need to be highlighted.
$keywords = array('php','net','fun');

// iterate through the list.
foreach($keywords as $keyword) {

    // replace keyword with **keyword**
    $str = preg_replace("/($keyword)/i","**$1**",$str);
}

The above will replacement of the keyword even if the keyword is a substring of any other bigger string. To replace only the keyword as full words you can do:

$str = preg_replace("/\b($keyword)\b/i","**$1**",$str);
codaddict
Try to use this code on something like this: `The cat is funny`. The output will be: `The cat is **fun**ny`.
Crozin
Yes, let's whinge instead of trying to improve the answer. codaddict needs only to cuddle `($keyword)` with `\b` either side, and it'll work as intended.
rjh
@Crozin: that is what OP wants. He wants to do the replacement even if the keyword is a substring of any bigger word.
codaddict
Oh, and if we're being pedantic, you should wrap $keyword with preg_quote() as it could conceivably contain regex metacharacters.
rjh
One more thing: you need /i to match PHP as the OP wants.
rjh
and how the scrip, which menchion the whole word, if it contain the keyword? keyword "fun", string - the cat is funny, result - the cat is ** funny**
Syom
A: 
$words = 'php|net|func';

echo preg_replace("/($words)/i", '**$1**', $a);
kemp