簡體   English   中英

替換preg_replace中的字符串

[英]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...";
?>

我想突出顯示特定詞。

例如phpnetfunc

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

謝謝前進。

您可以執行以下操作:

// 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);
$words = 'php|net|func';

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM