0

I don't understand why my really simple regex react like that, I've never been in this situation before:

$string = "you are the best pirate of the world";
if (preg_match_all("/pira|pirate|wor|world/", $string, $output)) {
    // $output => array(array('pira', 'wor'));
}

http://www.phpliveregex.com/p/meS : on this link you will have a bette view. So here, the output is "pira" and "wor" whereas I want to have "pirate" and "world". I must have missed something.

How to make it match the exact word ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
KeizerBridge
  • 2,707
  • 7
  • 24
  • 37
  • The first alternative that matches makes the regex engine stop checking the other alternatives on the right. Use `"/wor(?:ld)?|pira(?:te)?/"`. Or, if you are matching whole words, use word boundaries - `"/\b(?:pira|pirate|wor|world)\b/"` – Wiktor Stribiżew Dec 05 '17 at 21:37
  • Thank you I've done it but I don't undestand why it reacts like that, why stop and why doesn't take the exact occurence. – KeizerBridge Dec 05 '17 at 21:40
  • 2
    Read [*Remember That The Regex Engine Is Eager*](https://www.regular-expressions.info/alternation.html) – Wiktor Stribiżew Dec 05 '17 at 21:41
  • Yes but we can not say that this is a valid match when it output the occurence that contain the half of the letters. this is common sense and logic. – KeizerBridge Dec 05 '17 at 21:42
  • First match wins. That's how it works. What's being output doesn't "contain the half of the letters", it contains exactly what you're telling it to match. – Patrick Q Dec 05 '17 at 21:47

0 Answers0