使用数组作为strpos针 [英] Using an array as needles in strpos
本文介绍了使用数组作为strpos针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何搜索字符串时使用 strpos
的针阵列?例如:
How do you use the strpos
for an array of needles when searching a string? For example:
$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
if(strpos($string, $find_letters) !== false)
{
echo 'All the letters are found in the string!';
}
由于使用本时,它不会工作,这将是很好,如果有这样的事
Because when using this, it wouldn't work, it would be good if there was something like this
推荐答案
@戴夫从<一个更新的代码段href=\"http://www.php.net/manual/en/function.strpos.php#107351\">http://www.php.net/manual/en/function.strpos.php#107351
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
使用方法:
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
if (strposa($string, $array, 1)) {
echo 'true';
} else {
echo 'false';
}
将返回真正
,因为阵列
奶酪$ C $, C>。
更新:提高code与停在第一针的发现:
Update: Improved code with stop when the first of the needles is found:
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $query) {
if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
}
return false;
}
$string = 'Whis string contains word "cheese" and "tea".';
$array = array('burger', 'melon', 'cheese', 'milk');
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found
这篇关于使用数组作为strpos针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文