[英]Get specific words from a string that is after one word but before another?
Was wondering the best way to get words from a string, but any words that come after a specified word and before another. 想知道从字符串中获取单词的最佳方法,但是在指定单词之后和之前的单词之前的任何单词。
Example : 示例:
$string = "Radio that plays Drum & Bass music";
I would like to then echo out the 'Drum & Bass' part, so any words after plays and any words before music (in between play & music) 我想回声一下'Drum&Bass'部分,所以播放后的任何单词和音乐前的任何单词(在播放和音乐之间)
any ideas? 有任何想法吗?
Jamie 杰米
One way: 单程:
preg_match('/plays (.*) music/', $string, $match);
echo $match[1];
Use preg_match_all()
with a regex that uses lookaround assertions and word boundaries : 将
preg_match_all()
与使用外观断言和字边界的正则表达式一起使用:
preg_match_all('/(?<=\bplays\b)\s*(.*?)\s*(?=\bmusic\b)/', $string, $matches);
Explanation: 说明:
(?<=
- beginning of the positive lookbehind (if preceded by) (?<=
- 正面观察的开始(如果在前面) \\bplays\\b
- the word plays
\\bplays\\b
- 单词plays
)
- end of positive lookbehind )
- 积极的观察结束 \\s*
- match optional whitespace in between the words \\s*
- 匹配单词之间的可选空格 (.*?)
- match (and capture) all the words in between (.*?)
- 匹配(并捕获)其间的所有单词 \\s*
- match optional whitespace in between the words \\s*
- 匹配单词之间的可选空格 (?=
- beginning of the positive lookahead (if followed by) (?=
- 积极前瞻的开始(如果跟着) \\bmusic\\b
- the word music
\\bmusic\\b
- music
这个词 )
- end of the positive lookahead )
- 积极前瞻的结束 If you'd like the words to be dynamic, you can substitute them with a variable (using string concatenation, sprintf()
or similar). 如果您希望单词是动态的,可以用变量替换它们(使用字符串连接,
sprintf()
或类似)。 It's important to escape them before inserting the words in your regular expression though — use preg_quote()
for that purpose. 在插入正则表达式中的单词之前逃避它们很重要 - 使用
preg_quote()
来实现此目的。
Visualization: 可视化:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.