2017年初级PHP程序员笔试题
6.实现一个字符串截取的函数,类似于substr,必须能够截取中文这种多字节编码。假设每个中文也是一个字符,普通的数字、符号、字母也是一个字
符。(提示:GB编码的中文字符高位范围是 x81-xFE )
function GBSubstr($str, $len){
$count = ;
for($i=; $i
if($count == $len) break;
if(preg_match("/[/x8-/xff]/", substr($str, $i, 1))) ++$i;
++$count;
}
return substr($str, , $i);
}
function GBSubstr2($src, $start=, $length=){
$suffix="";
$len = strlen($src);
if ( $len <= $length ) return $src;
$cut_length = ;
for( $idx = ; $idx
$char_value = ord($src[$idx]);
if ( $char_value < x8 || ( $char_value & x4 ) )
$cut_length++;
else
$cut_length = $cut_length + 3;
}
$curstr = substr($src, , $cut_length) ;
preg_match('/^([/x-/x7f]|.{3})*/', $curstr, $result);
return $result[];
}
function CSubstr($str, $start=, $length, $charset="gbk", $suffix=false){
if(function_exists("mb_substr")){
return mb_substr($str, $start, $length, $charset);
}
$re['utf-8'] = "/[/x1-/x7f]|[/xc2-/xdf][/x8-/xbf]|[/xe-/xef][/x8-/xbf]{2}|[/xf-/xff][/x8-/xbf]{3}/";
$re['gb2312'] = "/[/x1-/x7f]|[/xb-/xf7][/xa-/xfe]/";
$re['gbk'] = "/[/x1-/x7f]|[/x81-/xfe][/x4-/xfe]/";
$re['big5'] = "/[/x1-/x7f]|[/x81-/xfe]([/x4-/x7e]|/xa1-/xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("", array_slice($match[], $start, $length));
if($suffix) {
return $slice ."…";
}
return $slice;
}
7.写一个遍历指定目录下所有子目录和子文件的函数(提示:可以使用递归的方法)
function dir_all ( $path ) {
$handler = opendir($path);
while (false!==($tmp = readdir($handler))) {
if(is_dir( "$path/$tmp" )) {
if ($tmp=="." | $tmp=="..") continue;
echo $tmp."
/n";
dir_all ("$path/$tmp");
} else {
echo $tmp ."
/n";
}
}
}
8.写出匹配邮箱地址和URL的两个正则表达式。类似下面的:
邮箱地址:user_name.first@example.com.cn
URL地址:http://www.example.com.cn/user_profile.php?uid=1
(提示:使用标准的正则表达式,就是PHP中preg_* 类的正则处理函数能够解析的正则)
邮箱://w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*/
URL:/^http:[/w]+/.[/w]+[/S]*/