热搜:NVER node 开发 php

关于特殊字符的过滤...我这有80分。。

2024-09-18 20:30:01
关于特殊字符的过滤...我这有80分。。

我现遇到一个问题,在提交表单时,对提交的内容要过滤掉特殊字符如:~!@#$%^&*()_+ ..这些
如我有一提交内容:生活*&)可以)(_更美的

如何过滤成:生活可以更美的。

我的做法是:
$str=str_replace("&","",$str);  
$str=str_replace(">","",$str);  
$str=str_replace(" $str=str_replace("=","",$str);
$str=str_replace("(","",$str);
$str=str_replace(")","",$str);
$str=str_replace("[","",$str);
$str=str_replace("]","",$str);
$str=str_replace(".","",$str);
$str=str_replace("*","",$str);
$str=str_replace("#","",$str);
$str=str_replace("$","",$str);
$str=str_replace("@","",$str);
$str=str_replace("-","",$str);
$str=str_replace("+","",$str);
$str=str_replace("&","",$str);  
$str=str_replace("!","",$str); 
$str=str_replace("~","",$str); 
$str=str_replace("^","",$str);
$str=str_replace("%","",$str);
$str=str_replace("'","",$str);
$str=str_replace("\"","",$str);

有没有更简便的方法。。求指教。。我这有80分。。


回复讨论(解决方案)

为何:$str=preg_replace("[`~!@#$%^&*()+=|{}':;',//[//]./?~!@#¥%……&*()??+|{}【】‘;:”“’。,、?]",'',$str);这样写,不行呢?

为何:$str=preg_replace("[`~!@#$%^&*()+=|{}':;',//[//]./?~!@#¥%……&*()??+|{}【】‘;:”“’。,、?]",'',$str);这样写,不行呢?

1.最大问题是正则没有边界符
2.转义不是//而是\,双引号内是\\
3.|被看作是或选择了
4.双引号内还有双引号么
……

大哥,那要怎么弄才行呀。

$p = str_split("&><=()[].*#$@-+&! ~ ^%'\"_");$s = '生活*&)可以)(_更美的';echo str_replace($p, '', $s);
生活可以更美的

明白了,多谢指点...只是不知全角的特符字符如¥)(,这些是否也能适用。。我试下

明白了,多谢指点...只是不知全角的特符字符如¥)(,这些是否也能适用。。我试下

全角的话改成用下面的函数

<?php function mb_str_split( $string, $encoding='UTF-8' ) {     # Split at all position not after the start: ^     # and not before the end: $     mb_regex_encoding($encoding);    mb_internal_encoding($encoding);     return preg_split('/(? # Prints: Array (     [0] => 火     [1] => 车     [2] => 票 )

对于切割串为数组,全角不适合
但手工书写的数组就是一样的了