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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改