Reputation: 129
I have a php string like as follows :
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2. I have tried something like below but not working.
$val = 'www';
$count = substr_count($string, $val);
Upvotes: 0
Views: 59
Reputation: 46602
With regex, which is faster and uses less memory then exploding, looping and counting:
<?php
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
echo preg_match_all('/\bwww\b/', $string, $matches); // 2
Upvotes: 0
Reputation: 163277
If you only want to match www, you could use \bwww\b
which will look for www
between word boundaries \b
with preg_match_all.
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
preg_match_all('/\bwww\b/', $string, $matches);
var_dump($matches);
Will result in:
array(1) {
[0]=>
array(2) {
[0]=>
string(3) "www"
[1]=>
string(3) "www"
}
}
Upvotes: 0
Reputation: 46602
Using explode() and array_count_values().
<?php
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
$arr = array_count_values(explode(" ", $string));
echo isset($arr['www']) ? $arr['www'] : 0; //2
Upvotes: 0
Reputation: 4066
This code will help you
Details: used explode
function to convert string into array
and finally used loop
with condition
<?php
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
$a=explode(" ",$string);
print_r($a);
$count=0;
foreach($a as $value)
{
if($value=="www")
{
$count++;
}
}
print_r($count);
?>
Upvotes: 1