我有下面的url,其中var_a应该始终是一个数字。我也不知道会有多少var_a:
http://localhost/url.php?var_a[]=298&var_a[]=299
如果用户在url中写入特殊字符,如何防止出现错误?
我已经做到了:
$data = preg_replace('/[^0-9'']/', '',$_GET['var_a']);
$data = str_replace("'", '', $data);
print_r ($data);// Array ( [0] => 298 [1] => 299 )
//This is ok, all number were printed
但我仍然会遇到一些特殊字符的错误,比如#%&
例如
http://localhost/url.php?var_a[]=298&var_a[]=#299
print_r ($data);// Array ( [0] => 298 [1] => )
//299 was not printed!
我该怎么解决这个问题?
据我所知,如果用户直接在URL中输入值,则无法修复此问题。原因是这些字符在URLS中有特殊的含义:#表示数据片段,%表示unicode值,&表示一个新变量。如果它来自表单,您可以使用两个选项:使用$_POST值,或者在提交值之前使用urlencode。Pound符号(#)在PHP中不起作用,有更多关于使用urlencode的信息。