Jamie Warren
Jamie Warren

Reputation: 143

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)

any ideas?

Jamie

Upvotes: 4

Views: 757

Answers (2)

Amal Murali
Amal Murali

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 lookahead

If 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:

Demo

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

One way:

preg_match('/plays (.*) music/', $string, $match);
echo $match[1];

Upvotes: 2

Related Questions