使用String的有限单词突出显示搜索到的单词

时间:2017-03-28 09:21:38

标签: php regex

我想突出显示搜索到的关键字,我在这里找到了解决方案,但它显示了整个字符串,突出显示匹配的单词 比赛前后我只想要10个字 这是我正在使用但不起作用

$text = preg_replace("/^.*?(.{0,1})\b($keyword)\b(.{0,1}).*?$/i", '\1<span class="highlight">\2</span>\3', $text);
echo $text ;

1 个答案:

答案 0 :(得分:0)

现在用php测试。有点像...

<?php
$src = 'twelve eleven ten nine eight seven six five four three two one KEYWORD one two three four five six seven eitht nine ten eleven twelve';
$keyword = "KEYWORD";
$regex = "/(.*?)((\w+\W+){0,10})($keyword\W+)((\w+\W+){0,10})(.*)/i";
$text = preg_replace("$regex", '\1<span class="highlight">\2\4\5</span>\7', $src);
echo $text;
?>

...应该这样做(突出显示关键字加10个字之前和之后。 可能还有更紧凑的替代品......

示例输入:

twelve eleven ten nine eight seven six five four three two one KEYWORD one two three four five six seven eitht nine ten eleven twelve

......输出......

twelve eleven <span class="highlight">ten nine eight seven six five four three two one KEYWORD one two three four five six seven eitht nine ten </span>eleven twelve