简体   繁体   English

php如何向上移动目录直到特定文件

[英]php how to move up the directory until a specific file

lets say i have a directory structure like this假设我有这样的目录结构

____
|  Root
    |_____
       Folder1
    |_____
       Folder2
         |_____
            Subfolder2.1
            Subfolder2.2
                 |______
                    Subfolder2.2.1

if i wanted to move upwards from Subfolder2.1 to the Root folder i would have to do ../../ and if i have to move from Subfolder2.2.1 to Root i would have to do ../../../ is there a way in php or in regular expression to write an expression that goes back up the directory until it finds a specific file name (root)如果我想从Subfolder2.1向上移动到Root文件夹,我将不得不执行../../而如果我必须从Subfolder2.2.1移动到Root我将不得不执行../../../有没有办法在 php 或正则表达式中编写一个返回目录的表达式,直到找到特定的文件名(根)

currently in symfony framework i'm doing something like $defaultTemplate = '::../../../../../app/Resources/views/'.$input->getOption('mytwigdest') to create a template inside a directroy目前在 symfony 框架中,我正在做类似$defaultTemplate = '::../../../../../app/Resources/views/'.$input->getOption('mytwigdest')在目录中创建模板

ofcourse this only works for one level of folders not its subfolders or its parent folder, what expression do i need to put in instead of the ../ so that it goes up the directories until it finds a specific directory name当然,这只适用于一级文件夹,而不是其子文件夹或其父文件夹,我需要输入什么表达式而不是../以便它向上移动目录,直到找到特定的目录名称

__ DIR __ and symfony's $this->container->getParameter('kernel.root_dir') would not work as it would give me the current file's path which is entirely different from where i'm creating a template using $defaultTemplate __ DIR __ 和 symfony 的$this->container->getParameter('kernel.root_dir')不起作用,因为它会给我当前文件的路径,这与我使用$defaultTemplate创建模板的位置完全不同

Although I'm not sure why you need to go with such a way to solve your problem, this will calculate number of parent directories ../ to a custom directory.尽管我不确定您为什么需要采用这种方法来解决您的问题,但这将计算父目录的数量../到自定义目录。 You only want to change the name.您只想更改名称。 Here it is Root :这是Root

str_repeat("../", count(explode(DIRECTORY_SEPARATOR , __FILE__)) - (1 + array_flip(explode(DIRECTORY_SEPARATOR , __FILE__))['Root']));

Put all things together:把所有东西放在一起:

$defaultTemplate = '::'.str_repeat("../", count(explode(DIRECTORY_SEPARATOR , __FILE__)) - (1 + array_flip(explode(DIRECTORY_SEPARATOR , __FILE__))['Root'])).'app/Resources/views/'.$input->getOption('mytwigdest');
 include($_SERVER['DOCUMENT_ROOT'].'/index.php');

Will always find the direct to root folder.总会找到直接到根文件夹的。 Note you need / after $_SERVER.请注意,在 $_SERVER 之后需要/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM