dpe77294 2015-08-10 10:08
浏览 59
已采纳

preg_match_all为两个单词,允许在中间的字符

what I'm trying to do is, given a string such as

trying to download some music, give me the details to download the music

get a matching result through preg_match_all that would give me something like

[0][0] => download some music
[0][1] => some
[1][0] => download the music
[1][1] => the

but I'm not able to achieve this. I'm using this pattern

§download(.*)music(.*)§

but the problem is that it just matches the first download (the one from download some music) and the last music (the one from download the music), while my goal is to find all occurrences and get the chars in between the two words (it should actually work for any number of words, but let's start with two).

Any help is appreciated, thanks! :)

UPDATE: After having the issue solved, I wrote an article on how this kind of regex can be used to make a gentle pattern match (or, rather, to compute pattern relevance in a given text): http://www.thecrowned.org/method-for-pattern-relevance-in-text

  • 写回答

1条回答 默认 最新

  • duandi5328 2015-08-10 10:11
    关注
    \bdownload\b(.*?)\bmusic\b
    
                  ^^
    

    Do a non greedy search.See demo.

    https://regex101.com/r/fM9lY3/29

    $re = "/\\bdownload\\b(.*?)\\bmusic\\b/"; 
    $str = "trying to download some music, give me the details to download the music"; 
    
    preg_match_all($re, $str, $matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重