Search code examples
phpregexpreg-match

Words finder regex fails


I'm using this pattern to check if certain words exists in a string:

/\b(apple|ball|cat)\b/i

It works on this string cat ball apple

but not on no spaces catball smallapple

How can the pattern be modified so that the words match even if they are combined with other words and even if there are no spaces?


Solution

  • Remove \b from the regex. \b will match a word boundary, and you want to match the string that is not a complete word.

    You can also remove the capturing group (denoted by ()) as it is not required any longer.

    Use

    /apple|ball|cat/i
    

    Regex Demo

    An IDEONE PHP demo:

    $re = "/apple|ball|cat/i"; 
    $str = "no spaces catball smallapple";
    preg_match_all($re, $str, $matches);
    print_r($matches[0]);
    

    Results:

    [0] => cat
    [1] => ball
    [2] => apple