有没有办法计算字符串中的主题标签并接收一个数字作为结束结果?
$string = 'This is a #0 and #1 works like #2';
$count_hashtags = count('#',$string);
echo $count_hashtags;
//Output: "3"
答案 0 :(得分:4)
$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]);
修改强> 然后你可以把它放在一个函数
中function countHashTags($string)
{
if(preg_match_all("/(#\w+)/", $string, $matches))
return count($matches[0]);
else
return 0;
}