简体   繁体   中英

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

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('/(?<=\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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM