假设我有一个颜色数组:
$colors = array('black','yellow','red');
$color = 'reddish';
如何计算它们出现的次数?因为substr_count()
可能很好地检测到"红色",但"微红色"将不包括在内。所以我需要精确匹配字符串,不管它之前或之后是什么。
$string = implode(' ', $colors);
echo substr_count($string, $color);
这样怎么样?
$colors = array('black', 'yellow', 'red');
$color = 'reddish';
$string = implode('|', $colors);
preg_match_all("/".$string."/i", $color, $matches);
print_r($matches); // will print an array of the matches
echo count($matches[0]); // will echo how many matches were made
这将输出1,如果$color等于"reddish yellow",则输出将是2,因为它匹配$colors数组中的"red"answers"yellow"。