0

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

3
  • 1
    Is this just an example or are you actually looking for single characters? Commented Aug 8, 2015 at 15:07
  • 1
    The expression "a" or "b" will just become a 1 there. Commented Aug 8, 2015 at 15:07
  • since it has two b and one a i need answer as 3. Commented Aug 8, 2015 at 15:08

2 Answers 2

2

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

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

2 Comments

I would be interested to know what is quicker/more efficient. running a functions a few times or loading the regex engine? Any ideas?
It's only worth profiling with a real example. String searches are the very domain of PCREs VM, and often quicker than PHPs VM doing loops and string comparisons. However that's only getting noticeable for longer input and alternatives there.
2

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

Comments

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.