2017-08-19 57 views
0

我有一個字符串:Chào Bạn如何刪除PHP中沒有引號的特殊字符?

在PHP中,我想將它轉換爲小寫,並刪除所有特殊字符,空格。

輸入:Chào Bạn

輸出:chaoban

在PHP代碼:

$string = 'Chào Bạn'; 
$newString = preg_replace('/\s+/', '', $string); 
echo strtolower($newString); 

$newString = chàobạn結果。

我無法刪除特殊字符。

+0

[正則表達式消毒(PHP)(https://stackoverflow.com/questions/3022185/regular-expression-sanitize-php) – vv01f

+0

音譯的可能的複製總是很棘手,但請查看['iconv()'](http://php.net/manual/en/function.iconv.php)。 – BenM

+1

爲什麼使用preg_replace刪除空格?這樣浪費計算能力。 – Andreas

回答

0

您可以使用下面的功能爲您的解決方案。

function clean($string) { 
    $string = strtolower($string); // Convert string into lower. 
    $string = str_replace(' ', '', $string); // Replaces all spaces . 

    return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars. 
} 
+0

您不需要'str_replace','preg_replace'處理它並且 – rndus2r

+0

您的回答是:'chobn' – vanloc

+0

Hi @Jalpa,添加行:'$ string = iconv('utf-8','ascii// TRANSLIT',$ string);''clean'()'函數中的'return'之前,並且remove行有'str_replace',因爲像@ rndus2r所說的那樣。它工作。編輯答案時,我會接受你的答案。 – vanloc

0

試試這個:

​​
+0

這不是一個答案,因爲它只會刪除所有非字母數字字符。 OP希望這些特殊字符回到正常字符。 – rndus2r