在字符串中搜索单词并更改格式

时间:2014-11-12 13:35:10

标签: php search

我想通过php

创建一个高亮标签搜索功能

当我搜索一部分单词时......整个单词都是彩色的

例如,这是一个示例文本:

文字:英国监管机构表示,交易员使用私人在线聊天室来协调他们的买卖,以转移货币价格。

当我搜索" th"输出如下:

文字:英国监管机构表示,交易员使用私人在线聊天室协调他们的买卖以转移货币价格他们的青睐。

所以...我试过这段代码......请帮我完成它。

这是一个算法:

$text= "British regulators say...";
foreach($word in $text)
{
  if( IS There "th" in $word)
   {
      $word2= '<b>'.$word.'</b>'
      replace($word with word2 and save in $text) 
   }
}

我怎么能用php语言呢?

5 个答案:

答案 0 :(得分:2)

function highLightWords($string,$find)
{
   return preg_replace('/\b('.$find.'\w+)\b/', "<b>$1</b>", $string); 
}

<强>用法:

$string="British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor.";
$find="th";
print_r(highLightWords($string,$find));

<强> Fiddle

在评论后修改:

  

...我怎么能为中间人物做这件事?例如&#34; line&#34;

非常简单,只需相应地更新正则表达式模式

return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string); 

<强> Fiddle

答案 1 :(得分:2)

使用strpos()查找您搜索的角色的位置。然后从该角色的识别位置开始读取,直到您找不到任何空格..

答案 2 :(得分:1)

应该更容易:

$word = "th";
$text = preg_replace("/\b($word.*?)\b/", "<b>$1</b>", $text);

答案 3 :(得分:1)

让我们说很多事情。

首先,如你所知,php是一个服务器端代码,所以,只要你不介意每次重新加载页面或使用ajax ......

我认为正确的方法是使用Javascript来实现这一目标。

那说要爆炸你需要使用另一个函数的文本,以确保获得了什么:

类似的东西:

$str = "Hello world. It's a beautiful day.";
$words = explode(" ",$str);

现在,Words var将包含爆炸的字符串。

现在你可以循环和替换(例如),然后重新构造字符串并打印它或做其他的。

答案 4 :(得分:1)

您可以使用以下代码

   <?php

    $string = "British regulators say traders used private online chatrooms to coordinate their buying and selling to shift currency prices in their favor";

     $keyword = "th";
     echo highlightkeyword($string , $keyword );

    function highlightkeyword($str, $search) {
        $occurrences = substr_count(strtolower($str), strtolower($search));
        $newstring = $str;
        $match = array();

        for ($i=1;$i<$occurrences;$i++) {
            $match[$i] = stripos($str, $search, $i);
            $match[$i] = substr($str, $match[$i], strlen($search));
            $newstring = str_replace($match[$i], '[#]'.$match[$i].'[@]', strip_tags($newstring));
        }

        $newstring = str_replace('[#]', '<b>', $newstring);
        $newstring = str_replace('[@]', '</b>', $newstring);
        return $newstring;

    }

    ?>

点击此处https://eval.in/220395