Extract words between two words with regex
14,857
You're close, but you're accessing the wrong index on $matches1
. $matches1[0]
will return the string that matched in preg_match();
Try $matches1[1]
;
Also, you need to enclose your regex in /
characters;
if (preg_match("/nights\s(.*)\spoodle/", "8 nights you doodle poodle", $matches1)) {
echo $matches1[1]."<br />";
}
Output
you doodle<br />
Related videos on Youtube
Author by
user1038814
Updated on June 04, 2022Comments
-
user1038814 almost 2 years
I have a string:
8 nights you doodle poodle
I wish to retrieve every thing between
nights
andpoodle
, so in the above example, the output should beyou doodle
.I'm using the below regex. Please can someone point out what I may be doing wrong?
if (preg_match("nights\s(.*)\spoodle", "8 nights you doodle poodle", $matches1)) { echo $matches1[0]."<br />"; }
-
FlyingGuy over 12 yearsSmells way to much like homework. Go and learn regex. Yes I know it is hard, but once you grok what all those weird match strings are about the better of you will be as a programmer.
-
Jared Farrish over 12 years@FlyingGuy - Homework questions are ok, as long as they are labeled
homework
. -
Nick Rolando over 12 yearsIf it was, I wouldn't have posted my answer.
-
maček over 12 years@Shredder, your answer is rubbish anyway.
-