douche5961 2013-06-27 17:23
浏览 32
已采纳

在php上突出显示文件中的多个单词?

I got a file filter.txt with words that I want to highlight on a string.

Filter.txt: test1 test2

My solution doesen't work:

    <?php
    $file = file_get_contents('/home/user/filter.txt', true);
    $keyword=$file;
    $str="This is a test1 and test2 and test3";

    $keyword = implode('|',explode(' ',preg_quote($keyword)));
    $str = preg_replace("/($keyword)/i","<b>$0</b>",$str);
    echo $str;
    ?>

Anyone?

  • 写回答

2条回答 默认 最新

  • drd2551 2013-06-27 17:56
    关注

    took me like 15 mins but I eventually got it :)

    <?php
      $file     = file_get_contents('/home/user/filter.txt', true);
      $keywords = $file;
      $str      = "This is a test1 and test2 and test3";
      $keywords = explode(" ", $keywords);
      $str      = preg_replace('/'.implode('|', $keywords).'/', '<b>$0</b>', $str);
      echo $str;
    ?>
    

    and this is expecting your filter.txt to be laid out like test1 test2 test3 etc. I'd suggest separating by new line or a pipe, |

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?