strpos不匹配 [英] strpos is not matching

查看:145
本文介绍了strpos不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要搜索一个字符串中,并得到相关的值,但在测试的功能,在每一个时间搜索词(标题应该发表提问)显示(给)只有一个输出标题, 11,11 !!!!如何解决?

  //测试序列
  $ ARR =阵列('标题,11,11','将,22,22','后,55,55','问,66,66');
  //定义你传递一个数组和一个搜索字符串搜索功能
  功能搜索($针,干草堆$){
    //遍历每个数组元素传递
    的foreach($如大海捞针V $){
      //如果存在匹配在第一位置
      如果(strpos($针,$ V)== 0)
        //返回当前数组元素
        返回$ V;
    }
    //否则retur假,如果未找到
    返回false;
  }
  //测试功能
  回声搜索(会,$ ARR);


解决方案

问题在于 strpos http://php.net/manual/en/function.strpos.php

草堆是第一个参数,第二个参数是针。

你也应该做一个 === 的比较为获得0。

  //测试序列
$ ARR =阵列('标题,11,11','将,22,22','后,55,55','问,66,66');
//定义你传递一个数组和一个搜索字符串搜索功能
功能搜索($针,干草堆$){
  //遍历每个数组元素传递
  的foreach($如大海捞针V $){
    //如果存在匹配在第一位置
    如果(strpos($ V,$针)=== 0)
      //返回当前数组元素
      返回$ V;
  }
  //否则retur假,如果未找到
  返回false;
}
//测试功能
回声搜索(会,$ ARR);

I want search one string and get related values, but in test the function, in each times search words(Title Or Would Or Post Or Ask) displaying(give) just one output Title,11,11 !!!! how can fix it?

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

解决方案

The issue lies in strpos. http://php.net/manual/en/function.strpos.php
The haystack is the first argument and the second argument is the needle.
You should also do a === comparison for getting 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);

这篇关于strpos不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆