1

我想搜索一个字符串并获取相关值,但在测试函数时,每次搜索单词(TitleWouldPostAsk)显示(给出)一个输出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);
4

3 回答 3

1

问题在于strposhttp://php.net/manual/en/function.strpos.php
haystack 是第一个参数,第二个参数是针。
您还应该进行===比较以获得 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-19T06:09:16.497 回答
0

此函数可能返回布尔值 FALSE,但也可能返回计算结果为 FALSE 的非布尔值,例如 0 或“”。请阅读有关布尔值的部分以获取更多信息。使用 === 运算符测试此函数的返回值。

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

于 2011-09-19T06:05:39.120 回答
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 返回 false ,但检查为 true,因为false == 0php 将. 为防止这种情况,您必须使用运算符(或,具体取决于您要执行的操作)。0false===!==

于 2011-09-19T06:05:59.933 回答