Question

I am trying to test a string for all pattern matches of several words which are the beginning of words. If not all patterns matched, I want to treat the query as False. The beginning of word testing is working, but I get duplicate matches, which I find surprising as I would have thought, that once one match was found for a word, it would not test again for that word. Perhaps I need to restrict the tests to one match somehow.

I imagined if I was testing for 3 words, then a successful test would return 3.

The return values are misleading as you can see from the example. I am getting a positive value, which is greater than the number of words I am testing. In the case of a non matching group, I am still getting a value higher than the number of words to be tested because of multiple matches of some words.

I guess I have not fully understood something or somehow I need to force an AND situation.

I have googled for answers, but none seem specific to my problem.

$image = 'After A!!BC DEF hello bugggy bad Sled bob bobert robob Triumph 2000 Roadster clearing bobby Sledmere ^ August 2014 ^ error';

$result = preg_match_all($query, $image, $matches);

$query = '#\b(bob|bug|sled)#i';  // ALL MATCH
Return Value 6 [ bob x 3, bug x 1, sled x 1]

$query = '#\b(bob|bug|led)#i'; // Two matches 'led' fails
Return Value 4 [ bob x 3, bug x 1, led x 0]
Was it helpful?

Solution

You can use several lookaheads:

$text = 'After A!!BC DEF hello bugggy bad Sled bob bobert robob Triumph 2000 Roadster clearing bobby Sledmere ^ August 2014 ^ error';   
$pattern = '~^(?=.*\bbob)(?=.*\bbug)(?=.*\bsled)~i';   
if (preg_match($pattern, $text)) echo 'OK!';

OTHER TIPS

try this

$image = 'After A!!BC DEF hello bugggy bad Sled bob bobert robob Triumph 2000 Roadster clearing bobby Sledmere ^ August 2014 ^ error';

$query = '#\b(bob|bug|sled)(.*?) #i';  // ALL MATC

preg_match_all($query, $image, $matches);

print_r($matches[0]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top