PHP - 将多个斜杠减少为单斜杠
我有一个正则表达式,用于将多个斜杠减少为单个斜杠。目的是读取之前使用 apache 中的 mod_rewrite 转换为人类可读链接的 url,如下所示:
http://www.website.com/about/me
这有效:
$uri = 'about//me';
$uri = preg_replace('#//+#', '/', $uri);
echo $uri; // echoes 'about/me'
这不起作用:
$uri = '/about//me';
$uri = preg_replace('#//+#', '/', $uri);
echo $uri; // echoes '/about/me'
我需要能够单独使用每个 url 参数,但在第二个中例如,如果我分解尾部斜杠,它将返回 3 个段而不是 2 个段。如果参数为空,我可以在 PHP 中验证是否有任何参数,但是当我使用该正则表达式时,如果正则表达式已经为我解决了这个问题,那就太好了,这样我就不需要担心段验证。
有什么想法吗?
I have a regular expression that I use to reduce multiple slashes to single slashes. The purpose is to read a url that is previously converted to a human readable link using mod_rewrite in apache, like this :
http://www.website.com/about/me
This works :
$uri = 'about//me';
$uri = preg_replace('#//+#', '/', $uri);
echo $uri; // echoes 'about/me'
This doesn't work :
$uri = '/about//me';
$uri = preg_replace('#//+#', '/', $uri);
echo $uri; // echoes '/about/me'
I need to be able to work with each url parameter alone, but in the second example, if I explode the trailling slash, it would return me 3 segments instead of 2 segments. I can verify in PHP if any if the parameters is empty, but as I'm using that regular expression, it would be nice if the regular expression already take care of that for me, so that I don't need to worry about segment validation.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在这种情况下 str_replace 可能会更快
其次:使用修剪: http://hu.php .net/manual/en/function.trim.php
str_replace may be faster in this case
Secondly: use trim: http://hu.php.net/manual/en/function.trim.php
这会将字符串中的双斜杠转换为单斜杠,但此代码的优点是保留字符串的协议部分 (
http://
) 中的斜杠。This converts double slashes in a string to a single slash, but the advantage of this code is that the slashes in the protocol portion of the string (
http://
) are kept.对 $uri 运行第二次替换怎么样?
这样,尾部的斜杠就被删除了。一次完成这一切 preg_replace 打败了我:)
使用 ltrim 也可能是一种方法(可能甚至更快)。
How about running a second replace on $uri?
That way a trailing slash is removed. Doing it all in one preg_replace beats me :)
Using ltrim could also be a way to go (probably even faster).
解决此问题的一种方法是使用 preg_split,并将第三个参数设置为
PREG_SPLIT_NO_EMPTY
:One fix for this is to use preg_split with the third argument set to
PREG_SPLIT_NO_EMPTY
:您可以将所有三种替代方案组合成一个正则表达式
you can combine all three alternatives into one regexp
您可以通过
preg_split
拆分字符串,完全跳过清理过程。不过,您仍然需要处理空块。You may split the string via
preg_split
instead, skipping the sanitizing altogether. You still have to deal with the empty chunks, though.晚了,但所有这些方法也会删除
http://
斜线,但是这个。Late but all these methods will remove
http://
slashes too, but this.