PHP:删除不可打印的字符而不删除空格

时间:2009-08-26 19:35:01

标签: php sql-server

我知道这是一个常见的问题,但我发现的一切似乎都消除了空白区域。

我正在寻找一个正则表达式,它将删除不可打印的字符,而不会更改任何空格。这是一个所有用户输入都将被过滤的功能,这意味着您通常可以在键盘上键入的所有字符都是有效的。例如:您在西班牙语中看到的口音是有效的。基本上你可以使用UTF 8字符集显示任何内容。

因为这是 SQL Server ,我不认为“SET NAMES UTF8”方法会起作用。

这就是我所拥有的。

function stripNonPrintable($input) 
{
    return preg_replace('/[\x00\x08\x0B\x0C\x0E-\x1F]/', '', $input);
}

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

function stripNonPrintable($input) {
   $bad=array(
      '\x00\x08\x0B\x0C\x0E-\x1F'
   );
   $fixed=array(
      ''
   );
   return str_replace($bad, $fixed, $input);
}

答案 1 :(得分:0)

你总是可以先逃避空白:

    function stripNonPrintable($input) 
    {
        $input = preg_replace('/ /','%%%%SPACE%%%%%%', $input);
        $input = preg_replace('/\t/','%%%%TAB%%%%%%', $input);
        $input = preg_replace('/\n/','%%%%NEWLINE%%%%%%', $input);

        $input = preg_replace('/[\x00\x08\x0B\x0C\x0E-\x1F]/', '', $input);

        $input = str_replace('%%%%SPACE%%%%%%',    ' ', $input);
        $input = str_replace('%%%%TAB%%%%%%',     "\t", $input);
        $input = str_replace('%%%%NEWLINE%%%%%%', "\n", $input);

    }

不优雅,但有效。