简体   繁体   English

PHP - Sanitize字符串删除数字

[英]PHP - Sanitize string removes numbers

I am attempting to define allowed characters in an array, and then sanitize strings based on this array. 我试图在数组中定义允许的字符,然后根据此数组清理字符串。 The below code works pretty good except that it removes chars 0-9 too! 下面的代码工作得很好,除了它也删除了字符0-9!

Could someone please explain why this is? 有人可以解释一下这是为什么吗?

Code: 码:

    <?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";

?>

Output: 输出:

mmddyyyy
Another--test-

Sidenote (edit): This is used in conjunction with a database but it goes beyond the DB, the data in the DB is used to write powershell scripts which import users into Active Directory, and many characters are not allowed, plus the old system only allowed these characters also. Sidenote(编辑):这与数据库结合使用,但它超出了数据库,DB中的数据用于编写powershell脚本,用户将用户导入Active Directory,不允许使用许多字符,仅使用旧系统也允许这些角色。

Thank you in advance, Wayne 先谢谢你,韦恩

Going off of what @andrewsi said with the allowed chars not being added to the array, I figured out how to add them properly. 关于@andrewsi所说的允许的字符没有添加到数组中,我想出了如何正确添加它们。 The below code shows they are added, and the outputs of the test strings. 下面的代码显示了它们的添加以及测试字符串的输出。

There's probably a better way to do this, so I added it to the community wiki. 可能有更好的方法,所以我将它添加到社区维基。

<?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";

?>

Output: 输出:

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

07mm04dd1776yyyy
Another-07041776-test-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM