php/正则表达式:“链接化”博客标题
我正在尝试编写一个简单的 PHP 函数,它可以接受像
Topic: Some stuff, Maybe some more, it's my stuff?
这样的
字符串,并返回
topic-some-stuff-maybe-some -more-its-my-stuff
因此:
- 小写
- 删除所有非字母数字非空格字符
- 用连字符替换所有空格(或空格组)
我可以使用单个正则表达式来执行此操作吗?
I'm trying to write a simple PHP function that can take a string like
Topic: Some stuff, Maybe some more, it's my stuff?
and return
topic-some-stuff-maybe-some-more-its-my-stuff
As such:
- lowercase
- remove all non-alphanumeric non-space characters
- replace all spaces (or groups of spaces) with hyphens
Can I do this with a single regex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很多框架都提供了这个
CodeIgniter的函数:
http://bitbucket.org/ellislab/ codeigniter/src/c39315f13a76/system/helpers/url_helper.php#cl-472
wordpress (代码中有更多内容):
http://core.trac.wordpress.org/浏览器/trunk/wp-includes/formatting.php#L814
Many frameworks provide functions for this
CodeIgniter:
http://bitbucket.org/ellislab/codeigniter/src/c39315f13a76/system/helpers/url_helper.php#cl-472
wordpress (has many more in the code):
http://core.trac.wordpress.org/browser/trunk/wp-includes/formatting.php#L814
您可以使用一个
preg_replace
来完成此操作:从技术上讲,您可以使用一个正则表达式来完成此操作,但这更简单。
抢先响应:是的,它不必要地使用正则表达式(尽管非常简单),不必要地大量调用
strtolower
,并且它不考虑非英语字符(他甚至不给出编码);我只是满足OP的要求。You can do it with one
preg_replace
:Technically, you could do it with one regex, but this is simpler.
Preemptive response: yes, it unnecessarily uses regular expressions (though very simple ones), an unecessarily big number of calls to
strtolower
, and it doesn't consider non-english characters (he doesn't even give an encoding); I'm just satisfying the OP's requirements.为什么正则表达式被认为是解决所有生活问题的万能灵丹妙药(仅仅因为 preg_match 中的低级回溯发现了癌症的治疗方法)。这是一个不求助于正则表达式的解决方案:
不走整个 UTF-8 路线:
给出
Why are regular expressions considered the universal panacea to all life's problems (just because a lowly backtrace in a preg_match has discovered the cure for cancer). here's a solution without recourse to regexp:
Without going the whole UTF-8 route:
gives