PHP
<?php
$tt1="b a b c";
echo substr_count($tt1,"a"or"b");
?>
由于这个词同时包含a和b,我希望结果为3。我正在尝试将输出设为3.但是我得到了0.请帮助
答案 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
只会查找一个子字符串。
较短的选项是使用preg_match_all
代替(返回计数):
$count = preg_match_all("/a|b/", $tt1);
(一旦寻找替代品,也只是遍历字符串。更容易适应更多的子串。可以寻找单词\b
边界等。但是,如果您之前已经听过/读过有关正则表达式,那么这是唯一可取的。)< / p>