Все ответы здесь поддерживают функцию str_replace (), которая заменяет все вхождения в любом месте строки, а не только в начале. preg_replace () обеспечит точное совпадение только с начала строки:
function remove_path($file, $path = UPLOAD_PATH) {
return preg_replace("#^($path)#", '', $file);
}
Windows может быть проблемой, где разделители каталогов / и \. Сначала убедитесь, что вы заменили разделители каталогов:
function remove_path($file, $path = UPLOAD_PATH) {
$file = preg_replace("#([\\\\/]+)#", '/', $file);
$path = preg_replace("#([\\\\/]+)#", '/', $path);
return preg_replace("#^($path)#", '', $file);
}
Я бы поиграл с чем-то вроде следующего. Запишите realpath () и rtrim ().
function webpath($file) {
$document_root = rtrim(preg_replace("#([\\\\/]+)#", '/', $_SERVER['DOCUMENT_ROOT']), '/');
$file = preg_replace("#([\\\\/]+)#", '/', realpath($file));
return preg_replace("#^($document_root)#", '', $file);
}
echo webpath(__FILE__); // Returns webpath to self
echo webpath('../file.ext'); // Relative paths
echo webpath('/full/path/to/file.ext'); // Full paths