2011-03-30 87 views
2

我试图去除所有特殊字符并在所有单词之间添加破折号。删除特殊字符并在单词之间添加一个破折号php mysql

例子:

示例文本: 如何使东西,别的东西,和其他的东西。

例字符串:它应该如何看

$string = "How to make something, something else, and other stuff."; 

示例: 如何对做某事某事,别的,和其他-东西

我需要一个函数,将剥离所有特殊字符,而且在每个单词之间加上破折号“但是在最后一个单词之后不加破折号”。任何人有任何想法,我应该如何做到这一点?我认为这很简单。可能是一个preg_replace与正则表达式,这将解决特殊的字符问题,但添加破折号是我困惑的地方,我不知道该怎么办。

+0

你如何定义“特殊字符”?非字母数字字符?或者除了a-z之外的任何东西 – deceze 2011-03-30 00:11:29

回答

5

假设字符串是UTF-8:

$string = 'Höw to máke sòmething, something else, and other stuff'; 
$string = preg_replace('/[^a-z0-9]+/i','-', 
    iconv('UTF-8','ASCII//TRANSLIT',$string)); 
$string = trim($string,'-'); 
+0

问题在于它在最后一个单词之后添加了一个破折号。其他方面,这将很好。 – chris 2011-03-30 00:14:24

+0

嗯,好吧,如果你不想那样的话,我会编辑它......这只是最后的'''被'-'取代:) – Wrikken 2011-03-30 00:15:09

+0

酷似乎很好。我会在6分钟内接受你的答案。谢谢。 – chris 2011-03-30 00:16:56

2

后,已删除了非字母字符,可以explode()的空间,然后用破折号implode()

+0

这是一个好主意,但Wrikken的回答更多的是我一直在寻找的东西。感谢您的建议,非常感谢。 – chris 2011-03-30 00:17:58

1

我会爆炸的字符串的空间,然后用这样的破折号爆吧:

$string = trim($string); // removes white space from ends 
$string = preg_replace("/[^A-Za-z0-9]/","",$string); // removes special chars 
$string = explode(' ', $string); // separates the words where there are spaces 
$string = implode('-', $string); // puts the words back into a sentence separated by dashes 
echo $string; 

这可以明显地凝聚 - 但为了简单起见,这些是所需的步骤。

相关问题