phparraysstringstrstr

How to count value from strstr function php?


I try to get value after symbol '@' and count it. But this code doesn't give the correct result. How to fix it?

$t="Hi, I invite @nina and @nana to come to my party tomorow";
$arr=explode(' ', $t);
foreach($arr as $user ) {
$result=strstr($user, '@');
$total = $count($result);
}
echo $total;

Result = 1

Expected Result =2


Solution

  • Why don't you explode it with @?

    $t = "Hi, I invite @nina and @nana to come to my party tomorow";
    $arr = explode('@', $t);
    $total = count($arr) - 1;
    echo $total;
    

    EDIT: As suggested by @mickmackusa, if you want to avoid counting solitary @, you can count those on the side and then subtract.

    $t = "Hi, I invite @nina and @nana to come to my party tomorow";
    $arr = explode('@', $t);
    $solos = explode('@ ', $t);
    $total = count($arr) - 1 - count($solos);
    echo $total;