douken1726 2017-04-26 19:55
浏览 27

php限制搜索结果的文本

After some search and googling I found code for highlighting and limiting the search results within a text similar to this one:

$text = preg_replace("/^.*?(.{0,100})\b($word)\b(.{0,100}).*?$/mi", '\1<span class="highlight_word">\2</span>\3', $text);

Unfortunately I always get the complete $text back even though the contents of $word is placed within the span as intended.

My question is now how I may reduce the contents of $text to just show 100 characters before and after the search result (contents of $word). I also checked the regular expression in several variants using a webportal and got the desired result. Nevertheless my php code is not showing what is intended. Any help is really appreciated as I assume there is a very stupid error on my side.

  • 写回答

1条回答 默认 最新

  • dongyishen5796 2017-04-26 20:32
    关注

    When you use the m flag, ^ and $ match the beginning and end of lines, not the beginning and end of the string. So this only matches and replaces in a single line of $text at a time, and non-matching lines are left alone.

    If you want to match across multiple lines, use the s modifier. That permits . to match newlines, but ^ and $ still match only the beginning and end of $text.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#网络安全#的问题:求ensp的网络安全,不要步骤要完成版文件
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥20 使用Photon PUN2解决游戏得分同步的问题
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序