例如abcdefghijkladgs我要查询第二个a出现的位置,应该怎么写?

解决方案 »

  1.   

    $str = 'abcdefghijkladgs';

    echo strpos($str,'a',2);
      

  2.   

    那如果是第三个a呢?例如
    abcdefghijkladgsakk
    谢谢~
      

  3.   

    搞错料,
    可以explode('a',$str)切成数组,再算。
      

  4.   


    function check($s, $s1, $n){
    $j = 0;
    $x = 0;
    $y = 0;
    for($i = 0; $i < strlen($s); $i++){
    if($index = strpos($s, $s1, $y + 1)){
    $j++;
    if($j == $n){
    $x = $index;
    break;
    }else{
    $y = $index;
    }
    }
    }
    return $x;
    }
    $s = 'afsdfhsafdfkljsldfj';
    $s1 = 'f';
    echo check($s, $s1, 2);细节判断自己改改吧
      

  5.   

    改了下function check($s, $s1, $n){
    $s = '@'.$s;
    $j = $x = $y = 0;
    for($i = 0; $i < strlen($s); $i++){
    if($index = strpos($s, $s1, $y? ($y + 1):$y)){
    $j++;
    if($j == $n){
    $x = $index;
    break;
    }else{
    $y = $index;
    }
    }
    }
    return $x - 1;
    }
    $s = 'afsdfhsafdfkljsldfj';
    $s1 = 'f';
    echo check($s, $s1, 2);
      

  6.   


    $str = 'abcdefghijkladgsabcdefghijkladgs';
    function getPos($str, $sonStr, $iIndex=0) {

    static $aPos = array();
    $ipos = false;
    $ipos = strpos($str, $sonStr, $iIndex);
    if ($ipos !== false) {

    $aPos[count($aPos)] = $ipos;  
    getPos($str, $sonStr, $ipos+1);
    }
    return $aPos;
    }
    print_r(getPos($str, 'a'));out:Array
    (
        [0] => 0
        [1] => 12
        [2] => 16
        [3] => 28
    )
      

  7.   

    $n = 2; //$n=3
    $str = 'asdfghhasdfghsdfsdf';
    $pos = -1;
    for ($i = 0; $i < $n; $i++) {
    $pos = strpos($str, 'a', $pos + 1);
    if ($pos === false) break;
    }
    echo $pos;
      

  8.   

    一顿饭的功夫,就结贴啦。。
    还可以用正则函数
    $str = 'abcdefghijkladgs';

    preg_match_all('#a#',$str,$m,PREG_OFFSET_CAPTURE);
    $pos = 2;
    print_r($m[0][$pos-1][1]);