$string = 'opel bmw mercedes audi chrysler audi'; $keyword = 'audi'; PHP: How do I output just the number of occurences for audi in that string please (should be 2) ? Thanks.
That was quick. Thank you. Here's what I did: Let me know if it's ok: preg_match_all ( '/('.$keyword.')/', $string, $matches, PREG_PATTERN_ORDER ); echo count($matches[0]); PHP:
2 things. If your $keyword contains special characters, you should use preg_quote() on it. preg_match_all ( '/('. preg_quote($keyword, '/') .')/', $string, $matches, PREG_PATTERN_ORDER ); PHP: Second, preg_match_all() returns the number of full pattern matches. So you can directly do this: $amount = preg_match_all ( '/'. preg_quote($keyword, '/') .'/', $string, $matches); echo $amount; PHP: (No need for the grouping either) It's slightly faster. Also, you can use the i modifier to make it case-insensitive, if wanted.