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 />
Share:
14,857

Related videos on Youtube

user1038814
Author by

user1038814

Updated on June 04, 2022

Comments

  • user1038814
    user1038814 almost 2 years

    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 />"; 
    }
    
    • FlyingGuy
      FlyingGuy over 12 years
      Smells 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
      Jared Farrish over 12 years
      @FlyingGuy - Homework questions are ok, as long as they are labeled homework.
    • Nick Rolando
      Nick Rolando over 12 years
      If it was, I wouldn't have posted my answer.
    • maček
      maček over 12 years
      @Shredder, your answer is rubbish anyway.