PHP - Sanitize字符串删除数字

时间:2016-09-24 16:15:45

标签: php sanitization

我试图在数组中定义允许的字符,然后根据此数组清理字符串。下面的代码工作得很好,除了它也删除了字符0-9!

有人可以解释一下这是为什么吗?

代码:

    <?php

//Allowed characters within user data:
$symbols = array();
$symbols += range('a', 'z');
$symbols += range('A', 'Z');
$symbols += range('0', '9');
array_push($symbols,' ','-'); // Allow spaces and hyphens.

//----test 1

//data to test.
$someString = "07mm04dd1776yyyy";

//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/i", "", $someString));

echo "$someString\n";

//----test 2
$someString = "Another-07/04/1776-test-!@#$%^&*()[]\\;',./\"[]|;\"<>?";

//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/i", "", $someString));

echo "$someString\n";

?>

输出:

mmddyyyy
Another--test-

Sidenote(edit):它与数据库一起使用,但它超出了数据库,数据库中的数据用于编写powershell脚本,将用户导入Active Directory,并且不允许使用许多字符,以及旧系统也只允许这些字符。

提前谢谢你, 韦恩

1 个答案:

答案 0 :(得分:0)

关于@andrewsi所说的允许的字符没有添加到数组中,我想出了如何正确添加它们。下面的代码显示了它们的添加以及测试字符串的输出。

这可能是更好的方法,所以我将它添加到社区维基。

<?php

//Allowed characters within user data:
$symbols = array();
array_push($symbols,implode("",range('0', '9')));
array_push($symbols,implode("",range('a', 'z')));
array_push($symbols,implode("",range('A', 'Z')));
array_push($symbols,' ','-'); // Allow spaces and hyphens.

print_r($symbols);
echo "\n";

//----test 1

//data to test.
$someString = "07mm04dd1776yyyy";

//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/", "", $someString));

echo "$someString\n";

//----test 2
$someString = "Another-07/04/1776-test-!@#$%^&*()[]\\;',./\"[]|;\"<>?";

//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/", "", $someString));

echo "$someString\n";

?>

输出:

Array
(
    [0] => 0123456789
    [1] => abcdefghijklmnopqrstuvwxyz
    [2] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
    [3] =>  
    [4] => -
)

07mm04dd1776yyyy
Another-07041776-test-