计算字符串中的所有主题标签 - PHP

Is there a way to count the hashtags in a string and receive a a number as a ending result?

$string = 'This is a #0 and #1 works like #2';

$count_hashtags = count('#',$string);

echo $count_hashtags;

//Output: "3"
$string = 'This is a #0 and #1 works like #2';   // Result : 3
$string2= 'foo #bar baz######';                 //  Result : 1

preg_match_all("/(#\w+)/", $string, $matches);
echo count($matches[0]);

Edit: You could then put it inside a function

function countHashTags($string)
{
    if(preg_match_all("/(#\w+)/", $string, $matches))
        return count($matches[0]);
    else
        return 0;
}