2

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 />"; 
}
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
user1038814
  • 9,337
  • 18
  • 65
  • 86

2 Answers2

10

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 />
maček
  • 76,434
  • 37
  • 167
  • 198
0

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

Community
  • 1
  • 1
David Ryder
  • 1,291
  • 5
  • 14
  • 27