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

时间:2014-05-28 05:21:48

标签: php string

有没有办法计算字符串中的主题标签并接收一个数字作为结束结果?

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

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

echo $count_hashtags;

//Output: "3"

1 个答案:

答案 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;
}