从字符串中删除特殊字符

时间:2013-10-22 15:12:43

标签: php regex string preg-replace special-characters

我正在使用一个函数从字符串中删除特殊字符。

function clean($string) {
   $string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

这是测试用例

echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g

参考SO答案。 问题是如果'是我的字符串中的最后一个字符,就像我从excel文件中获取字符串America',如果我把它放在这个函数中,它就不会逃脱'。任何帮助当第一个和最后一个字符为'

4 个答案:

答案 0 :(得分:14)

尝试取代常规期望 改变

preg_replace('/[^A-Za-z0-9\-]/', '', $string);

preg_replace('/[^A-Za-z0-9\-\']/', '', $string);  // escape apostraphe

你可以str_replace它比preg_replace()更快更容易因为它不使用正则表达式。

$text = str_replace("'", '', $string);

答案 1 :(得分:6)

以上示例中更详细的方式,以下是您的字符串:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';

代码:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows:英文字母(大写和小写),0到9和字符!@#$%^&*().

Removes:所有html标签,以及上述

以外的特殊字符

答案 2 :(得分:0)

乍一看,我认为addslashes功能可能是一个起点。 http://php.net/manual/en/function.addslashes.php

答案 3 :(得分:0)

绝对是一个更好的模式,但这适用于整个字符串:

preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", '', $string);

如果你需要在字符串中的单词周围替换它们,你必须使用\ b作为单词边界。此外,如果要在开头或结尾替换倍数,则需要在这些位置添加+。