2012-07-04 100 views
50

如何從PHP中的字符串中刪除所有非字母數字字符?使用preg_replace刪除所有非字母數字字符

這是代碼,我目前使用:

$url = preg_replace('/\s+/', '', $string); 

,只替換空格。

+1

可能的重複[如何刪除字符串中的非字母數字字符? (包括ß,Ê等)](http://stackoverflow.com/questions/7271607/how-do-i-remove-non-alphanumeric-characters-in-a-string-including-ss-e-etc ) – mario

+0

@mario:這與處理Unicode有點不同。我相信一個完美的副本存在tho ... –

+0

可能重複的[刪除非字母數字字符](http://stackoverflow.com/questions/659025/remove-non-alphanumeric-characters) – trejder

回答

101
$url = preg_replace('/[^\da-z]/i', '', $string); 
+6

[本答案支持unicode ](http://stackoverflow.com/a/17151182/99923) – Xeoncross

+10

如果其他人一時被Xeoncross的評論乍一看困惑,他的觀點是答案*不支持Unicode字符。但是Xeoncross'link *的解決方案確實*。 – orrd

4
preg_replace('/[\s\W]+/', '', $string) 

似乎工作,實際上例子是PHP文件中關於preg_replace函數

+1

請記住,這將*保留*下劃線,因爲它們被視爲單詞字符並保留空格 –

+0

我不知道下劃線,但它不保留空格。 – lisovaccaro

3
$alpha = '0-9a-z'; // what to KEEP 
$regex = sprintf('~[^%s]++~i', preg_quote($alpha, '~')); // case insensitive 

$string = preg_replace($regex, '', $string); 
13

起初採取這是我會做它

$str = '[email protected]#[email protected]#$^@#$Hello%#$'; 

$outcome = preg_replace("/[^a-zA-Z0-9]/", "", $str); 

var_dump($outcome); 
//string(11) "qwertyHello" 

希望這幫助!

+1

這對非拉丁字母不起作用 –

12

不知道爲什麼沒有其他人已經提出這一點,但是這似乎是最簡單的正則表達式:

preg_replace("/\W|_/", "", $string) 

你可以看到它在這裏的行動,也:http://phpfiddle.org/lite/code/0sg-314

+1

同時最簡單和有效的是'preg_replace(「/ [\ W _] + /」,「」,$ string)''。 –

1

您可以使用,

$url = preg_replace('/[^\da-z]/i', '', $string); 

您可以使用Unicode字符,

$url = preg_replace("/[^[:alnum:][:space:]]/u", '', $string); 
相關問題