2015-12-22 192 views
4

是否可以使用preg_replaceregex替換大寫字母的小寫字母?使用preg_replace()和正則表達式替換大寫字母的小寫字母

例如:

以下字符串:

$x="HELLO LADIES!"; 

我想將其轉換爲:

hello ladies! 

使用preg_replace()

echo preg_replace("/([A-Z]+)/","$1",$x); 
+2

我不認爲你可以單獨使用'preg_replace',因爲沒有模式。爲什麼不使用'strtolower'? –

+0

可能的重複[如何將字符串轉換爲小寫preg \ _replace](http://stackoverflow.com/questions/9939066/how-to-transform-a-string-to-lowercase-with-preg-replace) –

+5

'strtolower()'是一種簡單的解決方案嗎? – RiggsFolly

回答

9

我認爲THI s是你要完成的任務:

$x="HELLO LADIES! This is a test"; 
echo preg_replace_callback('/\b([A-Z]+)\b/', function ($word) { 
     return strtolower($word[1]); 
     }, $x); 

輸出:

hello ladies! This is a test 

Regex101演示:https://regex101.com/r/tD7sI0/1

如果你只是希望整個字符串小寫雖然比剛上使用strtolower整件事。

+2

我不知道strtolower()和preg_replace()在一起會很容易。謝謝克里斯。 – starkeen

相關問題