2014-03-25 46 views
0

我想创建一个url友好的字符串(一个将只包含字母,数字和连字符)从用户输入:正则表达式来创建网址友好的字符串

  1. 去除不AZ所有字符,0 -9,空间或连字符
  2. 替换所有空格带连字符
  3. 与一个连字符

预期产出取代多个连字符:

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 

有没有办法用一个单一的正则表达式来做到这一点?

+0

是什么点2和3之间的区别? – Toto

回答

1

是的,@杰里是正确的说你不能在一个替代品中这样做,因为你试图用两个不同的项目(空间或短划线,取决于上下文)替换特定的字符串。我认为杰里的回答是解决这个问题的最好方法,但你可以做的其他事情是使用preg_replace_callback。这允许您评估一个表达式并根据匹配的内容对其进行操作。

$string = 'my project 
test project 
this is @ long str!ng with spaces and symbo!s'; 

$string = preg_replace_callback('/([^A-Z0-9]+|\s+|-+)/i', function($m){$a = '';if(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';}return $a;}, $string); 

print $string; 

这是什么意思呢:

  • /([^A-Z0-9]+|\s+|-+)/i这看起来对你的三个量词的任何一个(任何不是一个数字或字母,一个以上的空间,超过一个连字符)和如果它匹配任何一个,它会将它传递给函数进行评估。
  • function($m){ ... }这是评估比赛的功能。 $m将保存它找到的匹配项。
  • $a = '';设置为空字符串用于替换
  • if(preg_match('/(\s+|-+)/i', $m[1])){$a = '-';}如果我们的比赛(存储在$m[1]值)包含多个空格或连字符默认值,然后设置$a到一个破折号,而不是一个空字符串。
  • return $a;由于这是一个函数,我们将返回该值,并将该值放入字符串中找到匹配的任何位置。

Here is a working demo

0

由于您想用不同的东西替换每个东西,因此您必须在多次迭代中执行此操作。

对不起d:

1

我不认为有这样做的一种方式,但你可以减少内容替换的数量和在极端情况下,使用一个衬垫这样的:

$text=preg_replace("/[\s-]+/",'-',preg_replace("/[^a-zA-Z0-9\s-]+/",'',$text)); 

它首先删除所有非字母数字/空格/破折号,然后用一个空格替换所有空格和多个破折号。

相关问题