【问题标题】:strpos() show n character before and after specified wordstrpos() 在指定单词前后显示 n 个字符
【发布时间】:2015-03-29 12:11:22
【问题描述】:

我写了一个简单的搜索引擎,想在结果中显示一些文本,实际上我想在 SEARCH QUERY 之前显示 200 个字符,在 SEARCH QUERY 之后显示 200 个字符。

示例:

搜索查询:测试

结果:

呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜 BLAHBLAH BLAH BLAHBLAH BLAH BLAH BLAH BLAH BLAH 测试 BLAH BLAH 呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜呜……

我想要这个输出:

... BLAH BLAH BLAH BLAH 测试 BLAH BLAH BLAH BLAH ...

前后各三个点。

$text= $row["text"];
$find = $term;
$result = strpos($text, $find);

但我不知道如何将其设置为在 $text 中显示 $term 之前的 200 个字符和 $term 之后的 200 个字符。

【问题讨论】:

  • substr 可以帮助您。

标签: php mysql strchr stripos


【解决方案1】:

你可以使用substr()

substr() 函数返回字符串的一部分。

substr(string,start,length) 

阅读more

从文本的位置开始。减去 200(length) 将获得之前的字符,加上 200(length) 将获得之后的字符(这里添加了文本长度,因为我们从 $text 的第一个字母开始)

$text= $row["text"];
$find = $term;
$result = strpos($text, $find);
echo substr($text,($result-200>0)?($result-200):0,200)." ".$find." "
.substr($text,$result+strlen($find),200);

【讨论】:

  • 看起来不错,但有点不起作用,它会回显以 $term 开头的整个文本。
  • 这很棒。我如何将它与多个单词一起使用?例如,如果我们在大文本中寻找“快乐”这个词,并且您希望每个快乐的词都有这个功能,那么我们将如何做到这一点?
猜你喜欢
  • 2022-07-10
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多