preg_match_all 两个词,中间允许字符
preg_match_all for two words, allowing chars in the middle
我想做的是,给定一个字符串,例如
trying to download some music, give me the details to download the music
通过 preg_match_all 得到一个匹配结果,这会给我类似
[0][0] => download some music
[0][1] => some
[1][0] => download the music
[1][1] => the
但我无法做到这一点。我正在使用这种模式
§download(.*)music(.*)§
但问题是它只匹配第一个 download
(来自 download some music
的那个)和最后一个 music
(来自 download the music
的那个),而我的目标是找到所有出现的地方并获取两个单词之间的字符(它实际上应该适用于任意数量的单词,但让我们从两个开始)。
感谢任何帮助,谢谢! :)
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
\bdownload\b(.*?)\bmusic\b
^^
做一个 non greedy
search.See 演示。
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);
我想做的是,给定一个字符串,例如
trying to download some music, give me the details to download the music
通过 preg_match_all 得到一个匹配结果,这会给我类似
[0][0] => download some music
[0][1] => some
[1][0] => download the music
[1][1] => the
但我无法做到这一点。我正在使用这种模式
§download(.*)music(.*)§
但问题是它只匹配第一个 download
(来自 download some music
的那个)和最后一个 music
(来自 download the music
的那个),而我的目标是找到所有出现的地方并获取两个单词之间的字符(它实际上应该适用于任意数量的单词,但让我们从两个开始)。
感谢任何帮助,谢谢! :)
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
\bdownload\b(.*?)\bmusic\b
^^
做一个 non greedy
search.See 演示。
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);