php – 从字符串中删除特殊字符

前端之家收集整理的这篇文章主要介绍了php – 从字符串中删除特殊字符前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用一个功能从字符串中删除特殊字符. @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); // escape apostraphe

要么

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

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

猜你在找的PHP相关文章