May
24
2022
php对url规整化,剔除多余的上层目录、当前目录
作者:
绝缘体.. 发布:
2022-05-24 15:19 分类:
未分类 阅读:
抢沙发
php下,对url规整化,剔除多余的上层目录(../)、当前目录(./)。
有时会构造出这样形式的url
/test/valums-file-uploader-cf7bfb1//./client/client/../.././tests/120720093725954.jpg
虽然在url里可以正常使用,但毕竟太啰嗦,也不美观,应该剔除其中多余的 “./” 与 “../”,可以参考如下函数,使用preg正则表达式实现,使用前确认你的php环境有对preg正则表达式的支持。
/**
* 归整文件或目录路径
* @param string $path
* @return string
*/
function constrict_url_path($path) {
//转换dos路径为*nix风格
$path = str_replace('\\', '/', $path);
//替换$path中的 /xxx/../ 为 / ,直到替换后的结果与原串一样(即$path中没有/xxx/../形式的部分)
$last = '';
while ($path != $last) {
$last = $path;
$path = preg_replace('/\/[^\/]+\/\.\.\//', '/', $path);
}
//替换掉其中的 ./ 部分 及 // 部分
$last = '';
while ($path != $last) {
$last = $path;
$path = preg_replace('/([\.\/]\/)+/', '/', $path);
}
return $path;
}
微信扫一扫,打赏作者吧~