2011-09-19 73 views
1

我想寻找一个字符串,并得到相关的值,但在测试中的功能,在各次搜索词(Title或者Would或者Post或者Ask)显示(给)只有一个输出Title,11,11 !!!!如何解决它?strpos不匹配

// 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); 

回答

1

问题出在strposhttp://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); 
+0

一个===对比您有鹰的眼睛;-)你说得对。 +1 –

0

这个函数可以返回布尔值FALSE,但也可能返回一个非布尔值,其值为FALSE,如0或“”。有关更多信息,请阅读布尔部分。使用===运算符来测试此函数的返回值。

来源:http://php.net/strpos

0

改变这个检查:

// 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是真实的,因为php会将0视为false。为防止出现这种情况,您必须使用===运算符(或!==,具体取决于您要做什么)。