简体   繁体   中英

In string how to count recursive word using php

I am a still beginner for php all thing. I am stuck here .

I want to count word "run" in variable $all.

i am doing it in wrong way. Please help me with this.

$a="run";
$a1="run1";
$a2="run";
$a3="run2";
$a4="run";
$a5="run";
$a6="run";


$all="$a $a1 $a2 $a3 $a4 $a5 $a6";

$count=0;

while(strpos($all,'arun') !== false) 
{
    $count=$count+1;
}
echo $count;

Use PHP's inbuilt function:

substr_count

It returns number of times a substring (part of a string) is repeated in a string.

Example:

substr_count ($your_string , $substring);

It returns count of the number of times the substring is repeated.

Try this

$a="run";
$a1="run1";
$a2="run";
$a3="run2";
$a4="run";
$a5="run";
$a6="run";

$all="$a $a1 $a2 $a3 $a4 $a5 $a6";

$count = substr_count($all, 'run');

echo $count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM