[英]How can I tell the number of times a value from an array is in a string
想象一下,我有一个名为uselessKeywords的数组。 它具有值“ and”,“ but”,“ the”。
如果我也有一个带有“ cool,and,but,and”的字符串,那么我怎么知道该字符串中的值在多少次了?
可以执行类似的操作,但是您必须注意误报,例如andover
和thesaurus
。
$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
您可以使用foreach uselessKeywords遍历字符串
$count = 0;
foreach($uselessKeywords as $needle){
$count = $count + substr_count($str, $needle);
}
echo $count;
马克·B的改善(增加一些昏迷消除误报andover
和thesaurus
;我已经添加了前瞻,因为有些值可以是一个接一个):
$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));
尝试这个..
<?php
function uselessKeywordOccurances ($myString, $theArray) {
$occurances = array();
$myTestWords = preg_split("/,/", $myString);
for($i = 0; $i < count($myTestWords); $i++) {
$testWord = $myTestWords[$i];
if (in_array($testWord, $theArray)) {
array_push($occurances, $testWord);
}
}
$grouped = array_count_values($occurances);
arsort($grouped);
return $grouped;
}
$uselessKeywords = array("and", "but", "the");
$testWords = "cool,and,but,and,and,the,but,wonderful";
$result = uselessKeywordOccurances($testWords, $uselessKeywords);
var_dump($result);
?>
它应该返回出现的uselessKeywords,就像这样。
array(3) { ["and"]=> int(3) ["but"]=> int(2) ["the"]=> int(1) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.