【问题标题】:highlight multiple word from file on php?在php上突出显示文件中的多个单词?
【发布时间】:2013-06-25 07:57:42
【问题描述】:

我有一个文件 filter.txt,其中包含我想在字符串上突出显示的单词。

过滤器.txt: 测试1 测试2

我的解决方案不起作用:

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

有人吗?

【问题讨论】:

    标签: php string filter highlight words


    【解决方案1】:

    尝试修剪可能在第二个关键字后出现空格的内容

    $keyword=trim( file_get_contents("filter.txt",true) );
    

    【讨论】:

      【解决方案2】:

      花了我大概 15 分钟,但我最终明白了 :)

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

      这是希望您的 filter.txt 的布局类似于 test1 test2 test3 等。我建议用新行或管道分隔,|

      【讨论】:

      • 谢谢!它可以工作,但过滤器必须在最后一个关键字的末尾有一个空的“空格”
      猜你喜欢
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-29
      • 2018-03-05
      相关资源
      最近更新 更多