【问题标题】:To highlight text in a string in php在php中突出显示字符串中的文本
【发布时间】:2015-11-17 04:32:29
【问题描述】:

由于我是初学者,请帮助解决这个问题。我尝试使用以下代码突出显示字符串中的文本,但没有得到预期的结果。

foreach($modules as $comments)
    {
        foreach($block_words as $k=>$v)
        {

          foreach($v as $n)
          {
            $comments['Updated'] = (preg_replace("/\b($n)\b/i","<b>$n</b>",$comments['Updated']));  
          }

        }
    }

我用过这个,但是得到了输出 What &lt;b&gt;you&lt;/b&gt; trying &lt;b&gt;to&lt;/b&gt; say.................. Plz &lt;b&gt;clear&lt;/b&gt; and Neetttttttttt

请找出错误并帮助我解决问题。

【问题讨论】:

  • 您的意见和预期结果是什么?
  • $block_words=Array ( [0] => Array ( [word] => to ) [1] => Array ( [word] => you ) [2] => Array ( [word ] => clear ) [3] => Array ( [word] => good ) ) 和 $cmets['updated']='string..........array';如果它出现在 $cmets['updated'] 中,我想突出显示块词

标签: php regex


【解决方案1】:

试试这个:

   /*** quote the text for regex ***/
   $n = preg_quote($n);
   /*** highlight the words ***/
   $comments['Updated'] = preg_replace("/\b($n)\b/i", '<b>\1</b>', $comments['Updated']);

编辑

这是我使用的工作代码。

  $sentence = "What you are trying to say?";
  $wordsToHighlight = array("you", "to");
  $modifiedrawData = preg_replace('/'.implode('|', $wordsToHighlight).'/i', '<span style="color:green;"><b>$0</b></span>', $sentence);
  echo $modifiedrawData;

根据您的示例,假设$v 包含您要突出显示的单词。

 $comments['Updated'] = preg_replace('/'.implode('|', $v).'/i', '<span style="color:green;"><b>$0</b></span>', $sentence);

【讨论】:

  • 是的,我试过了,但我得到的结果是 尝试 说的...... ...请 和 Neetttttttttt 。这是你想说的原始字符串......请清除和 Neetttttttttt。请建议我解决这个问题的解决方案
  • @Developer 请尝试编辑部分中的代码。我也使用此代码突出显示单词,它工作正常,所以它一定适合你。
  • 谢谢。我试过了,但我得到了它的原样。你想说什么.....请清除和 Neetttttttttt
  • @Developer 我添加了一个例子
  • 是否可以在texarea中突出显示文本。
猜你喜欢
  • 2019-09-13
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2017-08-20
  • 2022-01-01
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多