11 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.
}
Run Code Online (Sandbox Code Playgroud)
这是测试用例
echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g
Run Code Online (Sandbox Code Playgroud)
参考SO答案.问题是如果'是我的字符串中的最后一个字符,就像我America'
从excel文件中获取一个字符串,如果我把它放在这个函数中,它就不会逃脱'
.当第一个和最后一个字符是'
use*_*317 14
尝试取代常规的期望变化
preg_replace('/[^A-Za-z0-9\-]/', '', $string);
Run Code Online (Sandbox Code Playgroud)
同
preg_replace("/[^A-Za-z0-9\-\']/", '', $string); // escape apostraphe
Run Code Online (Sandbox Code Playgroud)
要么
你可以str_replace 它比preg_replace()更快更容易 因为它不使用正则表达式.
$text = str_replace("'", '', $string);
Run Code Online (Sandbox Code Playgroud)
以上示例中更详细的方式,以下是您的字符串:
$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! ??? ?? ????? ??????! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text ?? ???? test 123 ?,.m,............ ~~~ ??]??}~?]?}"; ';
Run Code Online (Sandbox Code Playgroud)
码:
echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));
Run Code Online (Sandbox Code Playgroud)
Allows:
英文字母(大写和小写),0到9和字符 !@#$%^&*().
Removes:
所有html标签,以及除上述之外的特殊字符