preg_replace to capitalize a letter after a quote
I have names like this:
$str = 'JAMES "JIMMY" SMITH'
I run strtolower
, then ucwords
, which re开发者_StackOverflow中文版turns this:
$proper_str = 'James "jimmy" Smith'
I'd like to capitalize the second letter of words in which the first letter is a double quote. Here's the regexp. It appears strtoupper is not working - the regexp simply returns the unchanged original expression.
$proper_str = preg_replace('/"([a-z])/',strtoupper('$1'),$proper_str);
Any clues? Thanks!!
Probably the best way to do this is using preg_replace_callback()
:
$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('!\b[a-z]!', 'upper', strtolower($str));
function upper($matches) {
return strtoupper($matches[0]);
}
You can use the e
(eval) flag on preg_replace()
but I generally advise against it. Particularly when dealing with external input, it's potentially extremely dangerous.
Use preg_replace_callback
- But you dont need to add an extra named function, rather use an anonymous function.
$str = 'JAMES "JIMMY" SMITH';
echo preg_replace_callback('/\b[a-z]/', function ($matches) {
return strtoupper($matches[0]);
}, strtolower($str));
Use of /e
is be deprecated as of PHP 5.5 and doesn't work in PHP 7
Use the e modifier to have the substitution be evaluated:
preg_replace('/"[a-z]/e', 'strtoupper("$0")', $proper_str)
Where $0
contains the match of the whole pattern, so "
and the lowercase letter. But that doesn’t matter since the "
doesn’t change when send through strtoupper
.
A complete solution doesn't get simpler / easier to read than this...
Code: https://3v4l.org/rrXP7
$str = 'JAMES "JIMMY" SMITH';
echo ucwords(strtolower($str), ' "');
Output:
James "Jimmy" Smith
It is merely a matter of declaring double quotes and spaces as delimiters in the ucwords()
call.
Nope. My earlier self was not correct. It doesn't get simpler than this multibyte-safe title-casing technique!
Code: (Demo)
echo mb_convert_case($str, MB_CASE_TITLE);
Output:
James "Jimmy" Smith
I do this without regex, as part of my custom ucwords()
function. Assuming no more than two quotes appear in the string:
$parts = explode('"', $string, 3);
if(isset($parts[2])) $string = $parts[0].'"'.ucfirst($parts[1]).'"'.ucfirst($parts[2]);
else if(isset($parts[1])) $string = $parts[0].'"'.ucfirst($parts[1]);
You should do this :
$proper_str =
preg_replace_callback(
'/"([a-z])/',
function($m){return strtoupper($m[1]);},
$proper_str
);
You should'nt use "eval()" for security reasons.
Anyway, the patern modifier "e" is deprecated. See : PHP Documentation.
echo ucwords(mb_strtolower('JAMES "JIMMY" SMITH', 'UTF-8'), ' "'); // James "Jimmy" Smith
ucwords()
has a second delimiter parameter, the optional delimiters contains the word separator characters. Use space ' ' and "
as delimiter there and "Jimmy" will be correctly recognized.
精彩评论