PHP使用preg_match_all搜索和计算特定单词

I would like to ask for help with php regex. i have this code :

$search = preg_match_all("/$pattern+/", $file, $matches);

for example $pattern will be "car" and string to search for "car acar caracar" output should be 3 (1 = car,2 = caracar) but my output is 4

i want to not count a word with prefix like "acar" but it will count the pattern with suffix "caracar"

thanks for any ideas i hope its not hard to understand and sorry for bad english

You can use word boundary with preg_quote:

if ( preg_match_all("/\b" . preg_quote($pattern) . "/", $file, $matches) ) {
    print_r($matches); // or echo count($matches);
}