php检查多个值的字符串
我正在尝试构建一个函数,我可以用它来检查字符串中的多个值,这是一个类似于大海捞针的函数。我已将值拆分为一个数组,并尝试在数组中循环,并使用for each循环检查字符串中的值,但没有得到预期的结果。请参见下面的函数、一些示例和预期结果 功能php检查多个值的字符串,php,arrays,string,search,if-statement,Php,Arrays,String,Search,If Statement,我正在尝试构建一个函数,我可以用它来检查字符串中的多个值,这是一个类似于大海捞针的函数。我已将值拆分为一个数组,并尝试在数组中循环,并使用for each循环检查字符串中的值,但没有得到预期的结果。请参见下面的函数、一些示例和预期结果 功能 function find($haystack, $needle) { $needle = strtolower($needle); $needles = array_map('trim', explode(",", $needle));
function find($haystack, $needle) {
$needle = strtolower($needle);
$needles = array_map('trim', explode(",", $needle));
foreach ($needles as $needle) {
if (strpos($haystack, $needle) !== false) {
return true;
}
}
return false;
}
示例1
$type = 'dynamic'; // on a dynamic page, could be static, general, section, home on other pages depending on page and section
if (find($type, 'static, dynamic')) {
// do something
} else {
// do something
}
结果
这应该捕获$type包含静态还是动态的条件,并根据页面运行相同的代码
示例2
$section = 'products labels'; // could contain various strings generated by site depending on page and section
if (find($section, 'products')) {
// do something
} elseif (find($section, 'news')) {
// do something
} else {
// do something
}
结果
如果$section在products部分的页面上包含'products',则应特别捕获该条件。在news部分的页面上包含'news'
--
在返回所需结果时似乎不可靠,并且无法找出原因!非常感谢您的帮助 可能是这样的
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';
}
这将是真的,因为奶酪为什么这里有一个2路
查找
,可以派上用场
var_dump(find('dynamic', 'static, dynamic')); // expect true
var_dump(find('products labels', 'products')); // expect true
var_dump(find('foo', 'food foor oof')); // expect false
使用的功能
function find($str1, $str2, $tokens = array(" ",",",";"), $sep = "~#") {
$str1 = array_filter(explode($sep, str_replace($tokens, $sep, strtolower($str1))));
$str2 = array_filter(explode($sep, str_replace($tokens, $sep, strtolower($str2))));
return array_intersect($str1, $str2) || array_intersect($str2, $str1);
}
那么:
str_ireplace($needles, '', $haystack) !== $haystack;
由于下一行输入错误,您的
strtolower
调用没有执行任何操作,但此代码仍应按给定的方式工作——至少在这两种特殊情况下是如此。感谢您指出这一点,我已修改了上述函数。正如您所说,我相信函数工作正常,我可能在代码中使用的一些if/elseif/else语句中遇到了问题并出错。正如我所知,offset选项的作用是什么?offset指定您希望在字符串中的哪个点开始搜索。在这种情况下,我们希望从头开始搜索。