【发布时间】:2013-11-10 07:27:35
【问题描述】:
我在 StackOverflow 网站上注意到的一点:
如果您访问 StackOverflow.com 上问题的 URL:
网站将问题的名称添加到URL的末尾,因此变成:
"https://stackoverflow.com/questions/10721603/grid-background-image-using-imagebrush"
这很好,我知道这会使 URL 更有意义,并且可能是一种很好的 SEO 技术。
在 StackOverflow 上看到这个实现后我想要实现的目标
我希望在我的网站上实现相同的功能。我很高兴使用header() 301 重定向来实现这一点,但我正在尝试提出一个紧凑的脚本来解决这个问题。
到目前为止我的代码
Please see it working by clicking here
// Set the title of the page article (This could be from the database). Trimming any spaces either side
$original_name = trim(' How to get file creation & modification date/times in Python with-dash?');
// Replace any characters that are not A-Za-z0-9 or a dash with a space
$replace_strange_characters = preg_replace('/[^\da-z-]/i', " ", $original_name);
// Replace any spaces (or multiple spaces) with a single dash to make it URL friendly
$replace_spaces = preg_replace("/([ ]{1,})/", "-", $replace_strange_characters);
// Remove any trailing slashes
$removed_dashes = preg_replace("/^([\-]{0,})|([\-]{2,})|([\-]{0,})$/", "", $replace_spaces);
// Show the finished name on the screen
print_r($removed_dashes);
问题
我创建了这段代码,从外观上看它运行良好,它使字符串 URL 对人眼友好且可读。但是,我想看看是否可以简化或“收紧”一点......因为我觉得我的代码可能过于复杂。
我并不想把它放在一行上,因为我可以通过将函数相互嵌套来做到这一点,但我觉得可能有一种整体上更简单的方法来实现它——我正在寻找想法.
综上,代码实现如下:
- 删除所有“奇怪”字符并用空格替换它们
- 用破折号替换任何空格以使其对 URL 友好
- 返回一个不带任何空格的字符串,单词用破折号分隔,并且没有尾随空格或破折号
- 字符串可读(不包含百分号和 + 符号,就像简单地使用
urlencode()
感谢您的帮助!
可能的解决方案
我在写这篇文章时发现,我正在寻找所谓的 URL 'slug',它们确实对 SEO 有用。
I found this library on Google code 其中appears to work well in the first instance。
SO which can be found here 上还有一个值得注意的问题,还有其他例子。
【问题讨论】:
-
刚发现他们叫“蛞蝓”。
标签: php redirect url-rewriting preg-replace preg-match-all