coder
coder

Reputation: 37

php sub string count find many words

php

<?php
$tt1="b a b c";
echo substr_count($tt1,"a"or"b");
?>

Since the word has both a and b i want the result as three.I am trying to get the output as 3.But i am getting 0.please help

Upvotes: 0

Views: 64

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94652

You could try

<?php
$tt1="b a b c";
echo substr_count($tt1,'a') + substr_count($tt1,'b');
?>

OR to add the possiblilty to have any number of characters counted

<?php
function substr_counter($haystack, array $needles)
{
    $cnt = 0;
    foreach ( $needles as $needle) {
        $cnt += substr_count($haystack, $needle);
    }
    return $cnt;
}

$tt1="b a b c";
$total = substr_counter( $tt1, array('a', 'b') );
?>

Upvotes: 2

mario
mario

Reputation: 145482

substr_count will just look for one substring.

  • You can't let it search for two strings at once.
  • If you really want to, the simplest option would be calling it twice. (See RiggsFollys´ answer.)

The shorter option would be using preg_match_all instead (returns the count):

$count = preg_match_all("/a|b/", $tt1);

(Which also just traverses the string once looking for alternatives. Easier to adapt for more substrings. May look for word \b boundaries etc. But only advisable if you've heard/read about regexps before.)

Upvotes: 2

Related Questions