简体   繁体   English

我怎么知道一个数组中的值在一个字符串中的次数

[英]How can I tell the number of times a value from an array is in a string

Imagine I had an array called uselessKeywords. 想象一下,我有一个名为uselessKeywords的数组。 It has the values "and","but","the". 它具有值“ and”,“ but”,“ the”。

If I also have a string with "cool,and,but,and" in it, how can I tell how many times any values from the array are in the string? 如果我也有一个带有“ cool,and,but,and”的字符串,那么我怎么知道该字符串中的值在多少次了?

Something along the lines of this would do, but you'd have to watch for false positives, such as andover and thesaurus . 可以执行类似的操作,但是您必须注意误报,例如andoverthesaurus

$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));

You could loop over the string with a foreach uselessKeywords 您可以使用foreach uselessKeywords遍历字符串

$count = 0;
foreach($uselessKeywords as $needle){
    $count = $count + substr_count($str, $needle);
}

echo $count;

Improvement of Marc B (add some comas to eliminate the false positive andover and thesaurus ; I've added lookahead because some values can be one by one): 马克·B的改善(增加一些昏迷消除误报andoverthesaurus ;我已经添加了前瞻,因为有些值可以是一个接一个):

$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));

Try this.. 尝试这个..

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

It should return occurrences of the uselessKeywords, like so.. 它应该返回出现的uselessKeywords,就像这样。

array(3) { ["and"]=> int(3) ["but"]=> int(2) ["the"]=> int(1) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM