php子字符串计数找到很多单词

时间:2015-08-08 15:04:15

标签: php substring

PHP

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

由于这个词同时包含a和b,我希望结果为3。我正在尝试将输出设为3.但是我得到了0.请帮助

2 个答案:

答案 0 :(得分:2)

你可以尝试

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

答案 1 :(得分:2)

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

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

较短的选项是使用preg_match_all代替(返回计数):

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

(一旦寻找替代品,也只是遍历字符串。更容易适应更多的子串。可以寻找单词\b边界等。但是,如果您之前已经听过/读过有关正则表达式,那么这是唯一可取的。)< / p>