替换 preg_replace 中的字符串

问题描述 投票:0回答: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...";
?>

我想突出显示特定单词。

例如

php
net
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...

php regex preg-replace highlight
2个回答
5
投票

您可以执行以下操作:

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

即使关键字是任何其他更大字符串的子字符串,上述内容也会替换关键字。要仅将关键字替换为完整单词,您可以执行以下操作:

$str = preg_replace("/\b($keyword)\b/i","**$1**",$str);

0
投票
$words = 'php|net|func';

echo preg_replace("/($words)/i", '**$1**', $a);
© www.soinside.com 2019 - 2024. All rights reserved.