本帖最后由 snowlove 于 2013-06-17 18:27:34 编辑

解决方案 »

  1.   

    你使用了递归,return $pos; 在进入递归后会作用于 $pos=newtripos($str,$findstr,$count,$pos+1);
    而你并没有在这个分支里对 $pos 作处理(也就是将结果返回到上一级递归)
    我说的可能连我自己都不好理解,看代码:
    function newtripos($str,$findstr,$count,$off=0){
        $pos=stripos($str,$findstr,$off);
        $count--;
        if($count>0 && $pos!=false){
            $pos=newtripos($str,$findstr,$count,$pos+1);
        }
        return $pos;
    }
      

  2.   

    你的代码没问题。
    <?php
    function newtripos($str,$findstr,$count,$off=0){
        $pos=stripos($str,$findstr,$off);
        $count--;
        if($count>0 && $pos!=false){
            $pos=newtripos($str,$findstr,$count,$pos+1);
        }else{
            var_dump($pos);//程序执行到这里可以正确的打出$pos的值。继续执行就应该结束函数,返回$pos
            return $pos;  //这里就应该返回$pos的值了。
        }
    }
    $a="456123456455654466";
    $b=newtripos($a,'6',4); //可是这里$b 怎么没接收到$pos,是个null
    var_dump($b);
    ?>  把else体去掉,和没去掉有这么大差别?
      

  3.   

    差别大多了,因为没有去掉else时,相当于<?php if($count>0 && $pos!=false){
    $pos=newtripos($str,$findstr,$count,$pos+1);
                    return null;
    }else{
    var_dump($pos);
    return $pos;
    }
    }
    ?>
    而去掉else以后,则是<?php if($count>0 && $pos!=false){
    $pos=newtripos($str,$findstr,$count,$pos+1);
                    return $pos;
    }else{
    var_dump($pos);
    return $pos;
    }
    }
    ?>