Reputation: 13506
I'd like to do something like this:
$string = "Lorem ipsum DOLOR Sit amet";
...some magic here... -> $finalString
$finalString = "Lorem ipsum dolor Sit amet"
Basically I wan't to convert all words that are fully uppercase to full lowercase.
Upvotes: 2
Views: 117
Reputation: 68556
A sans regex solution...
<?php
$string = "Lorem ipsum DOLOR Sit amet";
$str_arr = explode(' ',$string);
foreach($str_arr as &$val)
{
if($val==strtoupper($val))
{
$val=strtolower($val);
}
}
echo $str= implode(' ',$str_arr); //"prints" Lorem ipsum dolor Sit amet
Upvotes: 3
Reputation:
This is what I suggested initially:
$finalString = preg_replace("/\\b[A-Z]+\\b/e", "strtolower(\"\\0\");", $string);
But, since PHP 5.5.0 onwards, the e
modifier in preg_replace has become deprecated. So the correct alternative would be preg_replace_callback:
$string = "Lorem ipsum DOLOR Sit amet";
$finalString = preg_replace_callback(
"/\\b[A-Z]+\\b/",
function($matches){
return strtolower($matches[0]);
},
$string
);
Upvotes: 6
Reputation: 3412
preg_replace_callback
is what you need.
$string = "Lorem ipsum DOLOR Sit amet";
$finalString = preg_replace_callback('/\b([A-Z]+)\b/', function($m) {
return strtolower($m[1]);
}, $string);
echo $finalString;
$m[1]
matches the first capturing group ([A-Z]+)
which matches uppercase words. \b
represent word boundaries.
Upvotes: 2
Reputation: 12168
Use preg_replace_callback()
with expression /\b[A-Z]+\b/
(\b
- start or end of word, [A-Z]+
- all charactes are uppercased and there is at least one character):
<?php
header('Content-Type: text/plain; charset=utf-8');
$string = 'Lorem ipsum DOLOR Sit amet';
$result = preg_replace_callback(
'/\b[A-Z]+\b/',
function($matches){
return strtolower($matches[0]);
},
$string
);
echo $result;
?>
Shows:
Lorem ipsum dolor Sit amet
P.S.: You may also update regex to lowercase only words, where at least 2 characters by:
/\b[A-Z]{2,}\b/
Upvotes: 1