2

I have a long path like this - /home/user/www/domain.net/public_html/system/dir/file.php, and I want crop this to get something like - /system/dir/file.php.

Now I am using this code:

$filename = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $filename);
$filename = join(DIRECTORY_SEPARATOR, array_slice(explode(DIRECTORY_SEPARATOR, $filename), -3, 3));

And it works, but I think there is a better solution.. Anyone know?

Thanks in advance.

4

3 回答 3

1

我认为您只需要 web 目录。所以你可以爆炸,/public_html因为它总是会在那里。

例如:

$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
$path = explode('/public_html', $filename);
echo $path[1];
于 2013-08-14T06:51:07.937 回答
1

您可以改用正则表达式。请参阅此示例:

$sFileName  = '/home/user/www/domain.net/public_html/system/dir/file.php';
$iCropCount = 3;
$sResult    = preg_replace('#.*?((\/[^\/]+){'.$iCropCount.'})$#', '$1', $sFileName));
//var_dump($sResult);

省略了操作DIRECTORY_SEPARATOR(因为上面示例的主要意义不在其中)

于 2013-08-14T06:40:23.480 回答
0

我找到了其他解决方案:

$filename = '/home/user/www/domain.net/public_html/system/dir/file.php';
explode($_SERVER['DOCUMENT_ROOT'], $filename);
$filename = end($filename);
于 2013-08-14T06:40:25.030 回答