Home  >  Article  >  Backend Development  >  数组查找字符串

数组查找字符串

WBOY
WBOYOriginal
2016-06-23 13:33:06994browse

有个数组,想要查找某个字符串出现的次数。

目前项目中用的是循环foreach遍历,然后计数,有没有更好的方法?


回复讨论(解决方案)

array_count_values() 返回一个数组,该数组用 input 数组中的值作为键名,该值在 input 数组中出现的次数作为值。 

http://php.net/manual/zh/function.array-count-values.php

可使用 preg_grep 函数,例

$a = array(  '有个数组,',  '想要查找某个字符串',  '出现的次数。',  '目前项目中用的是循环foreach遍历,',  '然后计数,',  '有没有更好的方法?',);$c = '数';echo count(preg_grep("/$c/", $a));

3

可知 数 这个字出现了 3 次

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn