正则表达式,将多个斜杠替换为一个
这似乎是一个很容易解决的问题,但它并不像看起来那么容易。我在 PHP 中有这个字符串:
////%postname%/
这是一个 URL,我永远不想在一行中出现多个斜杠。我从来不想完全删除斜线。
它应该是这样的:
/%postname%/
因为结构可能看起来不同,我认为我需要一个聪明的 preg 替换正则表达式。它需要像这样使用 URL:
////%postname%//mytest/test///testing
应将其转换为:
/%postname%/mytest/test/testing
It seems like an easy problem to solve, but It's not as easy as it seems. I have this string in PHP:
////%postname%/
This is a URL and I never want more than one slash in a row. I never want to remove the slashes completely.
This is how it should look like:
/%postname%/
Because the structure could look different I need a clever preg replace regexp, I think. It need to work with URLS like this:
////%postname%//mytest/test///testing
which should be converted to this:
/%postname%/mytest/test/testing
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
给你:
或:
甚至:
一个简单的
str_replace()
也能达到目的(如果连续斜杠不超过两个):Here you go:
Or:
Or even:
A simple
str_replace()
will also do the trick (if there are no more than two consecutive slashes):晚了,但所有这些方法也会删除
http://
斜线,但是这个。Late but all these methods will remove
http://
slashes too, but this.尝试:
Try:
这是使用 str_replace
that's using str_replace
我的解决方案:
My solution: