заменить строку в preg_replace - PullRequest
2 голосов
/ 20 марта 2010
<?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...

Спасибо заранее.

Ответы [ 2 ]

5 голосов
/ 20 марта 2010

Вы можете сделать следующее:

// 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 голосов
/ 20 марта 2010
$words = 'php|net|func';

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