编辑文件路径PHP


Edit filepath PHP

我的页面上有一个删除按钮,该删除按钮必须删除数据库中的某个条目(不太难),它必须删除保存删除按钮的文件所在的整个文件夹(也是可行的),但我也希望它删除放在其他地方的另一个文件夹,我不知道如何做到这一点。使用

dirname(__FILE__);

我可以获得持有删除按钮的文件所在的文件路径。结果是:

mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life

我也想删除的文件路径非常相似,但有点不同。最后3个文件夹是一个变量,所以它们的长度(以字符为单位)总是不同的。但是,必须从该文件路径中删除倒数第二个文件夹,因此它仍然存在:

 mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life

有没有办法用PHP实现这一点?使用substr或者类似的东西?

谢谢!

我认为这应该做到:

$folderToRemove = preg_replace( '#^(.*)/(.*?)/(.*?)$#', "$1/$3", dirname(__FILE__) );

您可以尝试在www.php.net/glob 中使用"glob"详细信息

你可以试试:

$files = glob('subdomains/dongen/httpdocs/*/logo4life');
foreach ($files as $file) {
    unlink($file); // note that this is very dangerous though, you may end up deleting a lot of files
}

您不需要任何花哨的东西,正如您所猜测的,一个简单的str_replace就可以做到:-

$file = 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life';
var_dump(str_replace('aandrijvingenenbesturingen/', '', $file));

输出:-

string 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life' (length=62)
$path = "mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life";
$regex = "/(.*'/).*'/(.*)/";
$matches = array();
preg_match($regex,  $path, $matches);
// var_dump($matches);
$new_path = $matches[1].$matches[2];
echo $new_path;

上面的代码使用preg_match来匹配字符串中的正则表达式。