2015-12-22 194 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

相关问题