2009-08-26 124 views
0

我知道這是一個常見問題,但我發現的一切似乎刪除空白。PHP:刪除不可打印的字符而不刪除空格

我正在尋找一個正則表達式,可以在不更改任何空格的情況下去除不可打印的字符。這是所有用戶輸入都將被過濾的功能,這意味着您通常可以在鍵盤上輸入的所有字符都是有效的。例如:你在西班牙文中看到的口音是有效的。基本上,您可以使用UTF 8字符集顯示任何內容。

因爲這是SQL Server,我不認爲「SET NAMES UTF8」方法將工作。

這是我的。

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

回答

1

嘗試這樣:

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

簡單,但有效。謝謝。 – 2009-08-27 13:12:36

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); 

    } 

不優雅,但它的作品。