[英]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.