問題描述
我希望創(chuàng)建一個 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
所以基本上我希望清除任何不是字母數(shù)字的內(nèi)容,同時仍然保持 URL 可讀.我創(chuàng)建了以下內(nèi)容,但我不確定它是否是最好的方法,或者它是否涵蓋了所有可能性:
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)))));
所以基本上:
- 修剪
- 用空替換任何非字母數(shù)字和空格
- 然后用破折號替換所有不是字母數(shù)字的內(nèi)容
- 用-替換-.
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.
推薦答案
正如您已經(jīng)指出的,在這種情況下不需要 urlencode(),trim() 也不需要.如果我理解正確,第 4 步是避免連續(xù)出現(xiàn)多個破折號,但它不會阻止超過兩個破折號.另一方面,連接兩個詞的破折號(如大規(guī)模")將被您的解決方案刪除,而它們似乎保留在 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 ) );
所以:
- 刪除任何既不是空格、破折號也不是字母數(shù)字的字符
- 用一個破折號替換任意連續(xù)數(shù)量的空格或破折號
- strtolower()
這篇關(guān)于清理放置在 URL 中的字符串的最佳方法是什么,例如 SO 上的問題名稱?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!