问题描述
我正在寻找一个URL字符串,就像一个SO用来链接问题的URL一样.我不打算重写URL(mod_rewrite).我正在寻找在页面上生成链接.
I'm looking to create a URL string like the one SO uses for the links to the questions. I am not looking at rewriting the url (mod_rewrite). I am looking at generating the link on the page.
示例:问题名称为:
Is it better to use ob_get_contents() or $text .= ‘test’;
URL最终为:
http://stackoverflow.com/questions/292068/is-it-better-to-use-obgetcontents-or-text-test
我感兴趣的部分是:
is-it-better-to-use-obgetcontents-or-text-test
因此,基本上,我希望在保持URL可读性的同时清除所有不是字母数字的内容.我创建了以下内容,但是我不确定这是最好的方法还是它涵盖了所有可能性:
So basically I'm looking to clean out anything that is not alphanumeric while still keeping the URL readable. I have the following created, but I'm not sure if it's the best way or if it covers all the possibilities:
$str = urlencode(
strtolower(
str_replace('--', '-',
preg_replace(array('/[^a-z0-9 ]/i', '/[^a-z0-9]/i'), array('', '-'),
trim($urlPart)))));
所以基本上:
- 修剪
- 替换任何非字母数字加空格的内容
- 然后用破折号替换所有非字母数字的
- 用-替换.
-
strtolower()
-
urlencode()
-可能不需要,但只是出于很好的考虑.
- trim
- replace any non alphanumeric plus the space with nothing
- then replace everything not alphanumeric with a dash
- replace -- with -.
strtolower()
urlencode()
-- probably not needed, but just for good measure.
推荐答案
您已经指出,在这种情况下不需要urlencode(),而且trim()也不需要.如果我理解正确,则第4步是避免连续出现多个破折号,但它不会阻止两个以上的破折号.另一方面,连接两个单词的短划线(例如大范围")将被您的解决方案删除,而它们似乎保留在SO上.
As you pointed out already, urlencode() is not needed in this case and neither is trim(). If I understand correctly, step 4 is to avoid multiple dashes in a row, but it will not prevent more than two dashes. On the other hand, dashes connecting two words (like in "large-scale") will be removed by your solution while they seem to be preserved on SO.
我不确定这是否真的是最好的方法,但这是我的建议:
I'm not sure that this is really the best way to do it, but here's my suggestion:
$str = strtolower(
preg_replace( array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'),
$urlPart ) );
所以:
- 删除任何既不是空格,破折号也不是字母数字的字符
- 用单个破折号替换任何连续数量的空格或破折号
- strtolower()
这篇关于清除字符串以放置在URL中的最佳方法是什么,例如SO上的问题名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!