首页 > 解决方案 > PHP正则表达式忽略字符组

问题描述

我正在尝试创建一个简单的函数,从路径或 URL 中删除不必要的斜杠。我可以preg_replace很好地删除两个正斜杠,只需要忽略它://,因为这将指示字符串的http://orhttps://部分:

$string = 'http://example.com/this//that/and/the/other/file.php';

echo preg_replace("/\/{2,}/", "/", $string);

// Outputs: http:/example.com/this/that/and/the/other/file.php

请注意如何在http://零件中删除两个正斜杠。当它前面有冒号时,如何修改此正则表达式以忽略两个正斜杠?所需的输出是:

http://example.com/this/that/and/the/other/file.php

标签: php

解决方案


尝试使用否定的lookbehind,例如/(?<!\:)\/+/,这基本上意味着“如果前面没有冒号,则匹配1个或多个斜杠”

代码:

$string = 'http://example.com/this//that/and/the/other/file.php';

echo preg_replace("/(?<!\:)\/+/", "/", $string);

你可以在这里看到一个活生生的例子。


推荐阅读