php - 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
解决方案
尝试使用否定的lookbehind,例如/(?<!\:)\/+/
,这基本上意味着“如果前面没有冒号,则匹配1个或多个斜杠”。
代码:
$string = 'http://example.com/this//that/and/the/other/file.php';
echo preg_replace("/(?<!\:)\/+/", "/", $string);
你可以在这里看到一个活生生的例子。
推荐阅读
- typescript - 如何使用另一个 TS 文件中的对象 (knockout.js)
- python-3.x - pandas sort_values 返回排序错误的数据框
- excel - 检查预约响应状态
- c# - assembly file load error when running application as windows service
- java - 发送后 10 秒使用 JDA 删除消息
- python - size_hint_max_x 没有设置宽度的最大限制
- json - Json-Schema 中的 OneOf 选择了一个案例及其否定
- javascript - 找到无限循环中询问的数字的算术平均值
- reactjs - 您将如何引用具有状态对象的数组来对其执行数组方法?
- c# - 如何在 Twitter 适配器上实现实体框架脚本存储