search
HomeBackend DevelopmentPHP Tutorial PHP中查找文件的相对路径也许绝对路径的工具

PHP中查找文件的相对路径或者绝对路径的工具
以前面试题目中有一题为求两个文件的相对路径,当时觉得没有电脑,书写代码太麻烦,没有做那个题目,今日工作比较闲遐,就想起这事来,完成了两个函数,代码未经过实际生产环境考验,如引用至生产环境,还请慎重阅读,主要是参考学习
查看源代码打印帮助

1
<?php 2
/**
3
 * 文件的相对路径或者绝对路径查找工具
4
 *
5
 * @author 清源教育<support@tsingyuan.cn >
6
 * @version $Id:v 1.0 ,2013/10/13 17:29:00
7
 * @copyright (c) Copyright;tsingyuan,2013
8
 */
9
 
10
/**
11
 * 返回文件的绝对路径
12
 *
13
 * @param string $filename
14
 * @return string
15
 */
16
function absoluteroute($filename)
17
{
18
    $split = '/\/|\\\/';
19
    $currentdir = preg_split($split, dirname(__FILE__));
20
    $dirarr = preg_split($split, $filename);
21
    $diracount = count($dirarr);
22
    $cda = count($currentdir);
23
    if(strpos(PHP_OS, 'WIN') !== false)
24
        $reg = '/\w\:/';
25
    else
26
        $reg = '/\//';
27
    if(!preg_match($reg, $dirarr[0]))
28
    {
29
        foreach($dirarr as $nk=>$name)
30
        {
31
            if($name == "." || $name == '..')
32
            {
33
                if($name == '..')
34
                    $filenamearr = array_slice($currentdir, 0, -($nk+1));
35
                if($name == '.' && $nk == '0')
36
                    $filenamearr = array_slice($currentdir, 0);
37
            }
38
            else
39
            {
40
                $filenamearr[] = $name;
41
            }
42
        }
43
        $filename = implode('/', $filenamearr);
44
    }
45
    return $filename;
46
}
47
 
48
/**
49
 * 返回两个文件的相对路径 (PS:^_^不错的php学习交流群:276167802,验证:csl,有兴趣的话可以加入进来一起讨论)
50
 * (为了保证输入的相对路径参数可用,故此函数依赖absoluteroute)
51
 *
52
 * @param string $filenamea
53
 * @param string $filenameb
54
 * @return string
55
 */
56
function relativeroute($filenamea, $filenameb)
57
{
58
    $split = '/\/|\\\/';
59
    $filenamea = absoluteroute($filenamea);
60
    $filenameb = absoluteroute($filenameb);
61
    $dira =preg_split($split, $filenamea);
62
    $dirb =preg_split($split, $filenameb);
63
    $flag = true;
64
    if(count($dira) >= count($dirb))
65
    {
66
        $tmp = array();
67
        $tmp = $dira;
68
        $dira = $dirb;
69
        $dirb = $tmp;
70
        $flag = false;
71
    }
72
    foreach($dira as $k=>$v)
73
        if($v != $dirb[$k])break;
74
 
75
    $dirr = array_slice($dirb, $k);
76
 
77
    $k == 1 ? $dtag  = '/' :  $dtag  = './';
78
    $result = $dtag.implode('/', $dirr);
79
    if(!$flag)
80
    {
81
        if($dira[0] == '')array_shift($dira);
82
        foreach($dirr as $kk=>&$v)
83
            ($kk+1) != count($dirr)?
84
                ($v ?
85
                    $v = '..' :
86
                    $v = '.'
87
                ) :
88
                $v = implode('/', array_slice($dira, $k)) ;
89
        $result = $dtag.implode('/', $dirr);
90
    }
91
    return $result;
92
}

本文出自 “清源教育” 博客,转载请注明此处,谢谢!
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool