如何在字符串中的字符串周围加粗两个单词,但不重叠句子?

时间:2012-02-21 05:37:12

标签: php string text

我需要加粗搜索词及其上下文(在句子中)。

考虑字符串:

  

Lorem ipsum dolor坐下来。 Consectetuer adipiscing elit。

如果搜索字词为Lorem ipsum,则结果应为:

  

Lorem ipsum dolor坐 amet。 Consectetuer adipiscing elit。

如果搜索结果为dolor sit,则结果应为:

  

Lorem ipsum dolor sit amet。 Consectetuer adipiscing elit。

如果搜索结果为Consectetuer,则结果应为:

  

Lorem ipsum dolor坐下来。 Consectetuer adipiscing elit。

你如何推荐我这样做(在php中)?

粗略搜索术语很容易:

$string = str_replace($query,'<strong>' . $query . '</strong>', $string);

但是如何在不重叠到下一个或上一个句子之前和之后包括两个单词?

2 个答案:

答案 0 :(得分:5)

您可以将字符串拆分为“句子”(完整分割(感叹号,问号等等))。

然后找到匹配单词的句子。

然后将该句子拆分为“单词”,并在匹配单词之前和之后的两个单词中添加一些标签。由于您只有一个句子可以处理,因此您需要检查以确保不会超出单词数组的范围。

然后将这些单词重新组合在一起,并将所有句子重新加入。


或者,您可以使用正则表达式和preg_replace(虽然这可能不是您想要关闭的道路,特别是如果您有一个选项,例如在明文上拆分 - 有一个引用类似于“你”有一个问题,你想使用正则表达式。现在你有两个问题。“):

$string = preg_replace("/\\b(\\w+ +){0,2}$query( +\\w+){0,2}\\b/i",
                       '<strong>$0</strong>',
                       $string);

正则表达式的工作原理如下(反斜杠在上面转义):

\b        | match a word boundary (ie match whole words)
(\w+ +)   | match a "word" followed by spaces (to separate it from the next word)
{0,2}     | match 0 to 2 of these such words (it will match as many as possible
          | up to 2)
$query    | match the '$query' string
( +\w+)   | regex for space (separating $query) followed by a word
{0,2}     | match 0 to 2 of these words (as many as possible up to 2)
\b        | match a word boundary (ie match whole words)

最后的/i表示“不区分大小写”。

替换字符串<strong>$0</strong>表示替换为“强”标记所包含的所有匹配字词。

这样做的原因是正则表达式不允许匹配句号。因此,它会在$query的任一侧抓取最多 2个单词,但禁止超越句号。

有一些常见的警告(您使用的任何方法都会有这种警告) - 您是否希望粗体覆盖问号?感叹号?撇号是否允许一个字?对于单词之间的非句点标点符号,您会怎么做?等

我建议改进上面的正则表达式(如果你想使用正则表达式):

  • 允许使用单词中的撇号:将\w+更改为[\w']+(也可以将其转换为PHP反斜杠)
  • 允许字之间的各种标点符号:将+更改为[\s\-&,]+(意为“空格”,“ - ”,“&amp;”,“,”允许在单词之间添加 - 根据自己的喜好添加更多内容,但不要将“。”添加进来以防止加粗超过句号。

答案 1 :(得分:1)

希望这有帮助

$str ="your whole string ";
if(isset($_POST['searchStr']))
{
$searchStr= $_POST['searchStr'];
$str= str_replace($searchStr,'<b>'. $searchStr.'</b>',$str);
}
echo "$str";

如果您想在功能

下使用不区分大小写的替代品
    str_ireplace() - Case-insensitive version of str_replace.