zahir hussain
zahir hussain

Reputation: 3739

replace string in preg_replace

<?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...

Upvotes: 1

Views: 19520

Answers (2)

codaddict
codaddict

Reputation: 455272

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

Upvotes: 5

Matteo Riva
Matteo Riva

Reputation: 25060

$words = 'php|net|func';

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

Upvotes: 0

Related Questions