Brian
Brian

Reputation: 294

Count all hashtags in a string - 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"

Upvotes: 2

Views: 704

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46900

$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;
}

Upvotes: 4

Related Questions