php sub string count 找到很多单词

php sub string count find many words

php

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

因为这个词同时有 a 和 b 我想要的结果是 three.I 我试图得到输出 3.But 我得到 0.please 帮助

你可以试试

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

或者增加计算任意数量字符的可能性

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

substr_count 将只查找一个子字符串。

  • 你不能让它同时搜索两个字符串。
  • 如果您真的想要,最简单的选择就是调用它两次。 (参见 。)

较短的选项将使用 preg_match_all 代替(returns 计数):

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

(这也只是在寻找替代方案时遍历字符串。更容易适应更多子字符串。可能会寻找单词 \b 边界等。但只有当你 heard/read 了解正则表达式时才可取之前。)