简体   繁体   English

使用preg_match从文件名中删除根目录

[英]Remove root directory from file name with preg_match

This is probably a super-easy thing do to, although I can't seem to get it right.I've also searched around a bit and can't seem to find an answer. 尽管我似乎无法正确地做到这一点,这可能是一件非常容易的事情,我也进行了一些搜索,似乎也找不到答案。

I'm trying to remove the root directory from $url string. 我正在尝试从$url字符串中删除根目录。

Here's my code: 这是我的代码:

<?php

    $files =  glob( $_SERVER['DOCUMENT_ROOT'] . '/files/*');

    $root = $_SERVER['DOCUMENT_ROOT'] . '/files/';

    foreach($files as $file)
    {
       $name = preg_replace("$root", "", $file);
       echo "$name";
    }

?>

Use str_replace() instead, like this: 改为使用str_replace() ,如下所示:

$name = str_replace("$root", "", $file);

Also, the double quotes aren't necessary. 另外,双引号不是必需的。 You could do like this to save (minor) execution time: 您可以这样做,以节省执行时间:

$name = str_replace($root, '', $file);

(PHP will parse text in double quotes to look for variables. In this case you can clarify directly that there IS a variable in there and nothing else. The text that it should be replaced with is empty (no need for parsing there). (PHP会在双引号中解析文本以查找变量。在这种情况下,您可以直接澄清其中是否有变量,而没有其他任何东西。应将其替换为的文本为空(无需在那里进行解析)。

看一下基

$name = basename($file);

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

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