I have a string:
8 nights you doodle poodle
I wish to retrieve every thing between nights
and poodle
, so in the above example, the output should be you 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 />";
}
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 />
You probably want something like this
if (preg_match("/nights\s(.*)\spoodle/", "8 nights you doodle poodle", $matches1)) {
echo $matches1[1]."<br />";
}
Check out rubular.com to test your regular expressions. Here is another relevant question:
Using regex to match string between two strings while excluding strings