如果它包含关键字,则突出显示字符串中的单词

时间:2010-03-20 16:42:56

标签: php

如果它包含关键字,如何编写脚本,哪个menchion全文? 示例:关键字“fun”,字符串 - 鸟很有趣,结果 - 这只鸟很有趣*。我做以下

     $str = "my bird is funny";
     $keyword = "fun";
     $str = preg_replace("/($keyword)/i","<b>$1</b>",$str);

但它只是关键字。我的鸟是有趣 ny

5 个答案:

答案 0 :(得分:49)

试试这个:

preg_replace("/\w*?$keyword\w*/i", "<b>$0</b>", $str)

\w*?匹配关键字前的任何字词(尽可能少)和\w*关键字后面的任何字词。

我建议您使用preg_quote来转义关键字:

preg_replace("/\w*?".preg_quote($keyword)."\w*/i", "<b>$0</b>", $str)

对于Unicode支持,请使用 u 标记和\p{L}而不是\w

preg_replace("/\p{L}*?".preg_quote($keyword)."\p{L}*/ui", "<b>$0</b>", $str)

答案 1 :(得分:5)

您可以执行以下操作:

 $str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);

示例:

$str = "Its fun to be funny and unfunny";
$keyword = 'fun';
$str = preg_replace("/\b([a-z]*${keyword}[a-z]*)\b/i","<b>$1</b>",$str);
echo "$str"; // prints 'Its <b>fun</b> to be <b>funny</b> and <b>unfunny</b>'

答案 2 :(得分:2)

<?php 
$str = "my bird is funny";

$keyword = "fun";
$look = explode(' ',$str);

foreach($look as $find){
    if(strpos($find, $keyword) !== false) {
        if(!isset($highlight)){ 
            $highlight[] = $find;
        } else { 
            if(!in_array($find,$highlight)){ 
                $highlight[] = $find;
            } 
        }
    }   
} 

if(isset($highlight)){ 
    foreach($highlight as $replace){
        $str = str_replace($replace,'<b>'.$replace.'</b>',$str);
    } 
} 

echo $str;
?>

答案 3 :(得分:-1)

这里我在字符串中添加了多次搜索以供参考

if(variable)

答案 4 :(得分:-2)

搜索并突出显示字符串,文字,正文和段落中的单词:

<?php $body_text='This is simple code for highligh the word in a given body or text';  //this is the body of your page
$searh_letter = 'this';  //this is the string you want to search for
$result_body = do_Highlight($body_text,$searh_letter);    // this is the result with highlight of your search word
echo $result_body;            //for displaying the result
function do_Highlight($body_text,$searh_letter){     //function for highlight the word in body of your page or paragraph or string
     $length= strlen($body_text);    //this is length of your body
     $pos = strpos($body_text, $searh_letter);   // this will find the first occurance of your search text and give the position so that you can split text and highlight it
     $lword = strlen($searh_letter);    // this is the length of your search string so that you can add it to $pos and start with rest of your string
     $split_search = $pos+$lword; 
     $string0 = substr($body_text, 0, $pos); 
     $string1 = substr($body_text,$pos,$lword);
     $string2 = substr($body_text,$split_search,$length);
     $body = $string0."<font style='color:#FF0000; background-color:white;'>".$string1." </font> ".$string2;
     return $body;
    } ?>