PHP面试中常见的字符串与文件操作题目
PHP面试中可能遇字符串函数以及文件操作相关函数的题目,总结如下,希望对大家有用:
1、PHP翻转中文字符串
function reverse ( $str ) {
$r = array ( ) ;
for ( $i = 0 ; $i < mb_strlen ( $str ) ; $i ++ ) {
$r [ ] = mb_substr ( $str , $i , 1 , 'UTF-8' ) ;
}
return implode ( array_reverse ( $r ) ) ;
}
echo reverse ( 'www.phpha.com天涯PHP博客' ) ;
//结果:'客博PHP涯天moc.ahphp.wwww'
2、PHP计算URL的文件后缀名
function getext ( $url ) {
$data = parse_url ( $url ) ;
$path = $data [ 'path' ] ;
$info = pathinfo ( $path ) ;
return $info [ 'extension' ] ;
}
echo getext ( 'http://blog.phpha.com/archives/1670.html?id=1670' ) ;
//结果:'html'
3、PHP计算两个文件的相对路径
function getrpath ( $path , $conpath ) {
$pathArr = explode ( '/' , $path ) ;
$conpathArr = explode ( '/' , $conpath ) ;
$dismatchlen = 0 ;
for ( $i = 0 ; $i < count ( $pathArr ) ; $i ++ ) {
if ( $conpathArr [ $i ] != $pathArr [ $i ] ) {
$dismatchlen = count ( $pathArr ) - $i ;
$arrleft = array_slice ( $pathArr , $i ) ;
break ;
}
}
return str_repeat ( '../' , $dismatchlen ) . implode ( '/' , $arrleft ) ;
}
$a = '/a/b/c/d/e.php' ;
$b = '/a/b/12/34/5.php' ;
echo getrpath ( $a , $b ) ;
//结果:'../../../c/d/e.php'
4、PHP遍历目录下的所有文件和文件夹
function finddir ( $dir ) {
$files = array ( ) ;
if ( is_dir ( $dir ) ) {
if ( $handle = opendir ( $dir ) ) {
while ( ( $file = readdir ( $handle ) ) !== false ) {
if ( $file != '.' && $file != '..' ) {
if ( is_dir ( rtrim ( $dir , '/' ) . '/' . $file ) ) {
$files [ $file ] = finddir ( rtrim ( $dir , '/' ) . '/' . $file ) ;
} else {
$files [ ] = rtrim ( $dir , '/' ) . '/' . $file ;
}
}
}
closedir ( $handle ) ;
}
}
return $files ;
}
print_r ( finddir ( 'F:/Golang/src' ) ) ;
/**结果:
Array
(
[0] => F:/Golang/src/hello.go
[1] => F:/Golang/src/src.exe
[test] => Array
(
[0] => F:/Golang/src/test/sss.txt
)
)
**/
文章转自:天涯
科大讯飞公司氛围 469人发布