0

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

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

0

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

Comments

0

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"
  }
}

Comments

0

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

1 Comment

what about if the string is : absjdjjd www dkkd www123 wwww

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.