我有一个这样的字符串:33,33,56,89,56
我需要找出如何使用两个JavaScript计算该字符串中类似字符串部分的数量?
喜欢33,33,56,89,56
有多少'33'和多少56
?使用JavaScript?
分裂或匹配在这里不起作用。实际情况是:有几个按钮具有相同的类,这里的产品行有一个自定义属性价格。现在点击事件我正在获取像$('.product_row').attr('price');
这样的值,现在我需要计算这里点击的产品和多少次?并且我需要计算它是否是被点击的类似产品,点击了多少次?
因此,它将动态生成33,33,56,89,56这个字符串。
帮助这些人。
答案 0 :(得分:1)
我不确定javascript,但这里是PHP:
$data = "33,33,56,89,56";
$dataAsArray = explode(",", $data);
$valueCount = array_count_values($dataAsArray);
echo $valueCount[56]; // Should output 2
编辑: 至于JavaScript,请看这里: array_count_values for JavaScript instead
答案 1 :(得分:0)
对于PHP,请参阅http://php.net/manual/en/function.substr-count.php
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3);
// the text is reduced to 's i', so it prints 0
echo substr_count($text, 'is', 3, 3);
// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10);
// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
JS:
var foo = 'This is a test';
var count = foo.match(/is/g);
console.log(count.length);
答案 2 :(得分:0)
试试吧
<?php
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>
<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);
alert(count.length);
</script>