我想创建一个url友好的字符串(一个将只包含字母,数字和连字符)从用户输入:正则表达式来创建网址友好的字符串
- 去除不AZ所有字符,0 -9,空间或连字符
- 替换所有空格带连字符
- 与一个连字符
预期产出取代多个连字符:
my project -> my-project
test project -> test-project
this is @ long str!ng with spaces and symbo!s -> this-is-long-strng-with-spaces-and-symbos
我目前做这3个步骤:
$identifier = preg_replace('/[^a-zA-Z0-9\-\s]+/','',strtolower($project_name)); // remove all characters which are not a-z, 0-9, space or hyphens
$identifier = preg_replace('/(\s)+/','-',strtolower($identifier)); // replace all spaces with hyphens
$identifier = preg_replace('/(\-)+/','-',strtolower($identifier)); // replace all hyphens with single hyphen
有没有办法用一个单一的正则表达式来做到这一点?
是什么点2和3之间的区别? – Toto