2011-06-28 41 views
1

我想刪除與指定的正則表達式不匹配的所有字符。如何刪除不包含在正則表達式中的所有字符

例如

$a = "hello my name is ,pate !"; 

echo notin_replace("[a-zA-Z]","",$a); 

hello my name is pate 
+0

雖然我與這裏的一些評論的基調不同意,我同意情緒 - 搜索會很好地爲你服務。這是一個關於正則表達式的SO問題,它有助於:http://stackoverflow.com/questions/89718/is-there-anything-like-regexbuddy-in-the-open-source-world,這裏是一個初學者的文章在PHP中使用正則表達式替換:http://www.webcheatsheet.com/php/regular_expressions.php –

回答

1

[^a-zA-Z]

心靈的CARRET在字符類的開始。它意味着沒有。

$a = "hello my name is ,pate !"; 

echo preg_replace("([^a-zA-Z ])", "", $a); 

hello my name is pate 

不要忘記給允許的字符添加空格,否則會被刪除。

1
preg_replace('/[^a-z ]/i', '', $a); // the /i is for case-insensitive 
            // put a space inside the expression 
1

使用preg_replacedocs

<?php 
$string = 'hello my name is ,pate !'; 
// this patter allows all alpha chars and whitespace (tabs, spaces, linebreaks) 
$pattern = '/[^a-zA-Z\s]/i'; 
$replacement = ''; 
echo preg_replace($pattern, $replacement, $string); 
?> 

嘗試在codepaste.org:http://codepad.org/ZoqcvtIu

+0

在字符類中放入小字母和大字母時,可以使用'i'修飾符。是修改器的原因? – hakre

+0

你的回答是正確的,但我不得不選擇一個,所以我採取了第一個。謝謝 –

+0

那麼,修飾語是毫無意義的,但也是無害的 –

相關問題