删除特殊字符并在单词之间添加一个破折号php mysql
问题描述:
我试图去除所有特殊字符并在所有单词之间添加破折号。删除特殊字符并在单词之间添加一个破折号php mysql
例子:
示例文本: 如何使东西,别的东西,和其他的东西。
例字符串:它应该如何看
$string = "How to make something, something else, and other stuff.";
示例: 如何对做某事某事,别的,和其他-东西
我需要一个函数,将剥离所有特殊字符,而且在每个单词之间加上破折号“但是在最后一个单词之后不加破折号”。任何人有任何想法,我应该如何做到这一点?我认为这很简单。可能是一个preg_replace与正则表达式,这将解决特殊的字符问题,但添加破折号是我困惑的地方,我不知道该怎么办。
答
假设字符串是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,'-');
答
我会爆炸的字符串的空间,然后用这样的破折号爆吧:
$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;
这可以明显地凝聚 - 但为了简单起见,这些是所需的步骤。
你如何定义“特殊字符”?非字母数字字符?或者除了a-z之外的任何东西 – deceze 2011-03-30 00:11:29