开发者

replace string in preg_replace

开发者 https://www.devze.com 2022-12-23 19:32 出处:网络
<?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
<?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 deve开发者_如何学编程loper mailing list documentation mailing list What is **PHP**? **PHP** is a widely-used...

Thanks advance.


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


$words = 'php|net|func';

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

精彩评论

暂无评论...
验证码 换一张
取 消