2013-11-15 41 views
-4

我有这样的字符串:33,33,56,89,56如何计算字符串中类似字符串部分/块的数量?

我需要找出如何计算该字符串中使用这两个JavaScript的类似字符串部分的数量?

like for 33,33,56,89,56有多少'33's和多少个56?使用JavaScript? 拆分或匹配不会在这里工作。实际情况是:对于产品行,有几个按钮具有相同的类和一个自定义属性价格。现在点击事件我正在获取像这样的值$('.product_row').attr('price');,现在我需要计算在这里点击了什么产品以及多少次?我需要计算它是否是一个类似的产品被点击,它被点击了多少次?

那么,它的33,33,56,89,56这个字符串会动态生成。

在这里帮助你们。

回答

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

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