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

Php 在字符串上搜索单词并更改格式,php,search,Php,Search,我不想通过php创建高亮标记搜索功能 当我搜索单词的一部分时…整个单词都是彩色的 例如,这是一个示例文本: 正文:英国监管机构表示,交易员利用私人在线聊天室协调买卖,以使汇率朝有利于他们的方向变化 当我搜索“th”时,输出如下: 正文:英国监管机构表示,交易员利用私人在线聊天室协调他们的买卖,以使货币价格对他们有利 所以…我试过这个代码…请帮我完成它 这是一个算法: $text= "British regulators say..."; foreach($word in $text) { i

我不想通过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) 
   }
}
$text=“英国监管机构说……”;
foreach($text中的单词)
{
if(在$word中是否有“th”)
{
$word2=''.$word''
替换($word为word2并保存在$text中)
}
}
如何使用php语言实现它?

应该更容易:

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

让我们说很多事情

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

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

也就是说,要分解文本,您需要使用另一个函数,以确保获得了什么:

比如:

$str = "Hello world. It's a beautiful day.";
$words = explode(" ",$str);
现在,单词var将包含分解的字符串


现在,您可以循环和替换(例如),然后重新构造字符串并打印它或执行其他操作。

您可以使用以下代码

   <?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;

    }

    ?>

检查这里

评论后编辑:

$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));
…我怎样才能为中间人物做这件事?例如“行”

非常简单,只需相应地更新regex模式

return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string); 
返回preg\u replace(“/\b(\w*$find\w*)\b/”、“$1”、$string);

使用strps()查找您搜索的字符的位置。。然后开始从已识别的字符位置读取到,直到找不到任何空格。

strpos可能会对您有所帮助,如果条件满足-然后用强标签包装-检查我下面的答案这些有什么帮助吗?是的,O/p是正确的,他们在
pre
标签中显示得如此粗体,所以没有出现过很多问题,但我想加粗这个词…不是其中的一部分。谢谢:)…我如何为中间字符加粗?例如“行”
return preg_replace("/\b(\w*$find\w*)\b/", "<b>$1</b>", $string);