Reputation: 294
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
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