Reputation: 143
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)
any ideas?
Jamie
Upvotes: 4
Views: 757
Reputation: 76646
Use preg_match_all()
with a regex that uses lookaround assertions and word boundaries:
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
)
- end of positive lookbehind\s*
- match optional whitespace in between the words(.*?)
- match (and capture) all the words in between\s*
- match optional whitespace in between the words(?=
- beginning of the positive lookahead (if followed by)\bmusic\b
- the word music
)
- end of the positive lookaheadIf you'd like the words to be dynamic, you can substitute them with a variable (using string concatenation, sprintf()
or similar). It's important to escape them before inserting the words in your regular expression though — use preg_quote()
for that purpose.
Visualization:
Upvotes: 2
Reputation: 78994
One way:
preg_match('/plays (.*) music/', $string, $match);
echo $match[1];
Upvotes: 2