我正在使用一个功能从字符串中删除特殊字符.
@H_404_1@function clean($string) {
$string = str_replace('','-',$string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/','',$string); // Removes special chars.
}
这里是测试用例
@H_404_1@echo clean('a|"bc!@£de^&$f g'); Will output: abcdef-g参考从SO答案.
问题是如果’是我的字符串中的最后一个字符,就像我从一个excel文件中得到一个字符串America’,如果我把这个函数放在这个函数中,它不会逃脱’.当第一个和最后一个字符是’
试图取代正常的期望
更改 @H_404_1@preg_replace('/[^A-Za-z0-9\-]/',$string);
更改 @H_404_1@preg_replace('/[^A-Za-z0-9\-]/',$string);
同
@H_404_1@preg_replace('/[^A-Za-z0-9\-\']/',$string); // escape apostraphe要么
你可以str_replace它比preg_replace()更快更容易因为它不使用正则表达式.
@H_404_1@$text = str_replace("'",$string);