我认为这是php基本而简单的问题。
$a = "";
$b = "red";
$c = "red,blue";
echo(count(explode(',',$a))); 1
echo(count(explode(',',$b))); 1
echo(count(explode(',',$c))); 2
我想在一个字符串
中计算多少字符串分隔','第二行和第三行是好的,但我认为
我希望第一行返回1; 有什么好办法吗? 感谢
答案 0 :(得分:1)
尝试使用substr_count
来计算字符串中有多少,
:
示例:
$a = "";
$b = "xs";
$c = "xs,oi";
echo(substr_count($a, ',')); // 0
echo(substr_count($b, ',')); // 0
echo(substr_count($c, ',')); // 1
计算单词数量:
示例:
$a = "";
$b = "xs";
$c = "xs,oi";
$a_words = substr_count($a, ',') + (strlen($a) ? 1 : 0);
$b_words = substr_count($b, ',') + (strlen($b) ? 1 : 0);
$c_words = substr_count($c, ',') + (strlen($c) ? 1 : 0);
echo $a_words; // 0
echo $b_words; // 1
echo $c_words; // 2
我们也可以做一个功能来做我们想要的事情:
function count_words($string, $deliminator = ",") {
return substr_count($string, $deliminator) + (strlen($string) ? 1 : 0);
}
echo count_words($a); // 0
echo count_words($b); // 1
echo count_words($c); // 2
答案 1 :(得分:1)
您可以使用array_filter。
$a = "";
$b = "red";
$c = "red,blue";
echo (count(array_filter(explode(',',$a), 'strlen')));
echo (count(array_filter(explode(',',$b), 'strlen')));
echo (count(array_filter(explode(',',$c), 'strlen')));