$path = '/home/to//my///site';
我正在尝试从上述路径中删除不必要的前向斜杠/
我正在努力获得这个结果
/home/to/my/site
我在使用str_replace
时失败了,因为我不知道反斜杠的数量。
$path = '/home/to//my///site';
我正在尝试从上述路径中删除不必要的前向斜杠/
我正在努力获得这个结果
/home/to/my/site
我在使用str_replace
时失败了,因为我不知道反斜杠的数量。
使用preg_replace
,您可以用一行代码实现这个效果:
preg_replace('#/+#','/',$str);
模式/+
将匹配正斜杠/
一次或多次,并用单个/
替换它。
当然,还有其他方法可以实现这一点,例如使用while
循环。
while( strpos($path, '//') !== false ) {
$path = str_replace('//','/',$path);
}
这将调用str_replace
直到所有出现的//
都被替换。如果您愿意牺牲可读性(不建议),您还可以在一行代码中编写该循环。while( strpos( ($path=str_replace('//','/',$path)), '//' ) !== false );
\/{2,}
来减少检查单个 /
的循环,这是不必要的。 - Muhammad Omer Aslampreg_replace('#(?<!:)/+#gm', '/', $str);
- Matt Kenefick如果有人想要从URL中删除额外的斜杠,而不删除http/https后的前两个斜杠:
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
感谢ツ Liverpool (如何使用'PREG'或'HTACCESS'删除URI中的多个斜杠)
您好,希望这篇翻译能对您有所帮助。
请将以下代码写入您的 .Htaccess 文件中并进行检查:
# Prevent double slashes in URLs, e.g. //Blog and /Home//About
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]
希望这能帮到您!
<?php
// 2 slashes
echo realpath('/etc//passwd') . PHP_EOL; // prints /etc/password
// 3 slashes
echo realpath('/etc///passwd') . PHP_EOL; // prints /etc/password
// 2 ..
echo realpath('/etc/../etc/passwd') . PHP_EOL; // prints /etc/password
?>
并且realpath()会展开所有符号链接,并解析输入路径中的“/ ./”、“/../”和额外的“/”字符,并返回规范化的绝对路径名。
在Windows下,realpath()将更改Unix样式的路径为Windows样式。
function get_absolute_path($path) {
$path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
$parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
$absolutes = array();
foreach ($parts as $part) {
if ('.' == $part) continue;
if ('..' == $part) {
array_pop($absolutes);
} else {
$absolutes[] = $part;
}
}
return implode(DIRECTORY_SEPARATOR, $absolutes);
}
var_dump(get_absolute_path('this/is/../a/./test/.///is'));
"this/a/test/is"
while(strlen($path) != (strlen($path = str_replace('//','/', $path))));
这段代码将双斜杠替换为单斜杠,只要它改变了长度。
realpath('/home/to//my///site')
来获取路径的真实路径。 - undefined