Ajay Krishna Dutta
Ajay Krishna Dutta

Reputation: 129

Counting the number of a specific word inside a php string

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

Answers (4)

Lawrence Cherone
Lawrence Cherone

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

The fourth bird
The fourth bird

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

Lawrence Cherone
Lawrence Cherone

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

Bilal Ahmed
Bilal Ahmed

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);
    ?>

sandbox output

Upvotes: 1

Related Questions