---
title: "通过面试题目学习php之编程题"
author: "student_lp"
date: "2014-07-22T10:39:00Z"
tags: ["php基础", "php编程"]
categories: ["互联网"]
slug: "php"
draft: false
lastmod: "2014-07-22T10:42:30Z"
id: 2094861
url: "https://student-lp.iteye.com/blog/2094861"
---

**1、编写一个自定义函数提取这段路径的的后缀名。**

**例如：http://www.baidu.com/hello/test.php.html?a=3&b=4需要取出php或.php**

```
function geturltype($url){
     $info=parse_url($url);
     return end(explode('.',$info['path']));
}
```

**2、写一个函数，算出两个文件的相对路径,如 $a = /a/b/c/d/e.php; $b= /a/b/12/34/c.php;**

**计算出$b相对于$a的相对路径应该是 ../../c/d**

```
function getRelPath($path1,$path2){
 $arr1 = explode("/", $path1);
 $arr2 = explode("/", $path2);
 array_shift($arr1);
 array_shift($arr2);
 
 for($i=0;$i<count($arr1);$i++){
  if($arr1[$i]!=$arr2[$i]){
   break;
  }
 }
 $depth = count($arr1)-$i-1;
 $path = "";
 for($j=0;$j<$depth;$j++){
  $path .= "/..";
 }
 for($j=$i;$j<count($arr2);$j++){
  $path .= "/".$arr2[$j];
 }
 echo substr($path, 1);
}
```

**3、以下是pHp标准的glob函数说明，请写出一个glob\_r函数，在标准glob的基础上支持列出所有子目录下的文件，且不返回所有目录。**

```
function glob_r($path){
 $files = array();
 $arr = glob($path."/*");
 foreach ($arr as $value){
  if(is_file($value)){
   $files[] = $value;
  }else{
   $temp = glob_r($value);
   $files = array_merge($files,$temp);
  }
 }
 return $files;
}
```

**4、写一个函数，能够遍历一个文件夹下的所有文件和子文件夹。** 

```
function read_file($path){
  $files = array();
  if(is_dir($path)&&file_exists($path)){
   $fp = opendir($path);
   while($file = readdir($fp)){
    if($file=='.'||$file=='..'){
     continue;
    }
    $files[] = $path.'/'.$file;
    if(is_dir($path.'/'.$file)){
     $temp = read_file($path.'/'.$file);
     $files=array_merge($files,$temp);
    }
   }
   closedir($fp);
  }
  return $files;
 }
```