PHP之几道面试题

1.二分查找算法

function two_find($arr,$low,$height,$k){
    if($low<=$height){
        $mid = intval(($low+$height)/2);
        if($arr[$mid]==$k){
            return true;
        }elseif($k<$arr[$mid]){
           return two_find($arr,$low,$mid-1,$k);
        }else{
           return two_find($arr,$mid+1,$height,$k);
        }
    }
    return false;
}
$arr = array(1,3,4,5,6,9,10,15,20,25,27,30);
$key = 20;
if(two_find($arr,min(array_keys($arr)),max(array_keys($arr)),$key)){
    echo "二分查找成功!";
}else{
    echo "二分查找失败!";
}
View Code

2.一个字符串中含有字母和数字,请输出所有数字的和,注意,连续的数字算一个数字。(比如输入字符串为“23abc23dbf23” 最后输入的值应该为:69)

function str_sum($str){
    $reg = '/[1-9]+[0-9]+/';
    preg_match_all($reg,$str,$marth);
    if(empty($marth)){
        return false;
    }
    return array_sum($marth[0]);
}
echo str_sum("12adb012add012");
View Code

3.php从url取出文件扩展名,尽可能高效和简单。

function get_url($url){
    $path = pathinfo($url);
    $extenstion = explode("?",$path['extension']);
    return $extenstion[0];
}
echo '从url取出文件扩展名,url为:http://m.cn/asdfasdf/2.asdf.adsfa.php?a=bbb&c=adfas,他的扩展名为:'.get_url('http://m.cn/asdfasdf/2.asdf.adsfa.php?a=bbb&c=adfas');
View Code

4.php中控制页面的显示状态为404,请写出PHp代码

echo "php中用header()函数是可以为返回页面添加404的头信息的,从而提示浏览器该网页找不到了。所以可以使用:header('HTTP/1.0 404 Not Found');或者:header('Status: 404 Not Found');后者是在FastCGI模式下使用的,在php代码中可以把两句直接同时写上。";

 

posted @ 2014-09-09 14:51  泡沫幻想  阅读(174)  评论(0编辑  收藏  举报