我想搜索一个字符串并获取相关的值,但在测试函数时,每次搜索单词(Title或Would或Post或Ask)时,只显示(给出)一个输出Title,11,11!怎样才能修复它?
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
//loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($needle,$v) == 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);发布于 2011-09-19 14:09:16
问题出在strpos。http://php.net/manual/en/function.strpos.php
干草堆是第一个参数,第二个参数是针。
您还应该进行===比较,以获得0。
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
//loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($v,$needle) === 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);发布于 2011-09-19 14:05:39
此函数可能返回布尔值FALSE,但也可能返回计算结果为FALSE的非布尔值,例如0或"“。有关更多信息,请阅读有关布尔值的部分。使用===运算符测试此函数的返回值。
来源:http://php.net/strpos
发布于 2011-09-19 14:06:00
更改此检查:
// if there is a match at the first position
if(strpos($needle,$v) == 0)
// return the current array element
return $v;至
// if there is a match at the first position
if(strpos($needle,$v) === 0)
return $v;或
// if there is a match anywhere
if(strpos($needle,$v) !== false)
return $v;如果未找到字符串,则返回strpos returns false,但检查false == 0将返回true,因为php将0视为false。为了防止出现这种情况,您必须使用===运算符(或!==,具体取决于您想要做什么)。
https://stackoverflow.com/questions/7466998
复制相似问题