doue9730 2009-01-14 01:07 采纳率: 100%
浏览 150

返回第一次出现字符串之前和之后的单词

I have a body of text returned from a search query, lets call it $body. Now, what I want to do is for the script to find the first occurrence of the search query, $query. I know I can find this first occurrence this with strripos.

Once found, I want the script to return a couple of words before the first occurrence of the string as well as a few words after the end of the first occurrence.

Essentially I'm trying to do what Google does with it's search results.

Any ideas on where I should start? My issue is that I keep returning partial words.

  • 写回答

4条回答 默认 最新

  • douxuan1284 2009-01-14 01:19
    关注

    You could:

    $words = explode(" ", $body);
    

    Creating an array of al the words in $body.

    $index  = array_search($query, $words);  
    $string = $words[$index - 1]." ".$words[$index]." ".$words[$index + 1];
    

    But you would get into trouble if the query consist out of more than 1 word.

    explode - array_search

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分