替换多个正斜杠

时间:2011-12-25 19:01:20

标签: php

我想用一个正斜杠替换多个正斜杠。

示例:

this/is//an//example - > this/is/an/example

///another//example//// - > /another/example/

example.com///another//example//// - > example.com/another/example/

谢谢!

编辑:这将用于修复具有多个正斜杠的网址。

3 个答案:

答案 0 :(得分:3)

preg_replace('#/+#','/',$str); 

preg_replace('#/{2}#','/',$str);

提示:使用str_replace进行如此简单的替换

  

用替换字符串

替换所有出现的搜索字符串
str_replace('/','/',$str);

Reference

答案 1 :(得分:2)

您可能想要使用正则表达式:

$modifiedString = preg_replace('|/{2,}|','/',$strToModify);

我使用{2,}代替+来避免替换单个'/'。

答案 2 :(得分:1)

使用正则表达式将一个或多个/ -es替换为/:

$string = preg_replace('#/+#', '/', $string);

我看到你想要创建一个有效的网址...你可能想看看realpath,或者更好的是第一条评论中的片段:

$path = '../gallery/index/../../advent11/app/';

$pattern = '/\w+\/\.\.\//';
while(preg_match($pattern, $path)) {
    $path = preg_replace($pattern, '', $path);
}
// $path == '../advent11/app/'

正如你所看到的,这也解决了../-es:)

相关问题