Reputation: 4729
I have a string: 'Some_string_to_capitalize' which I would like to transform to 'Some_String_To_Capitalize'. I have tried:
$result = preg_replace( '/(_([a-z]{1}))/' , strtoupper('$1') , $subject )
and
$result = preg_replace( '/(_([a-z]{1}))/' , "strtoupper($1)" , $subject )
I looked at the php man page and here on SO but found nothing. Apologies if this is a dup!
This is the equivalent SO question for Javascript.
Upvotes: 2
Views: 4552
Reputation: 2251
I think you want to use preg_replace_callback
:
In PHP 5.3+
<?php
$subject = 'Some_string_to_capitalize';
$result = preg_replace_callback(
'/(_([a-z]{1}))/',
function ($matches) {
return strtoupper($matches[0]);
} ,
$subject
);
For PHP below 5.3
function toUpper($matches) {
return strtoupper($matches[0]);
}
$result = preg_replace_callback('/(_([a-z]{1}))/', 'toUpper', $subject);
Upvotes: 9
Reputation: 7194
You've got some good answers posted thus far; however, I thought I'd post a variation just for kicks:
[updated] edited code snipped to be more terse:
<?php
$string = 'Some_strIng_to_caPitÃliZe';
echo mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
// Some_String_To_Capitãlize
The above code considers the following:
Unicode characters may be a part of the string; in which case, 'UTF-8'
should be a safe encoding:
mb_convert_case
using the flag MB_CASE_TITLE
takes care of words that come in with a mixed case, so we don't need to manually normalize and "_" is considered a word boundry.
The mb_convert_case
function works with PHP versions since 4.3.0
PHP Source for reference.
Upvotes: 1
Reputation: 3023
I think you want ucfirst not strtoupper. That will capitalize only the first letter of each match, not the entire match like strtoupper will. I'm also thinking you're going to need to switch to preg_replace_callback because your current syntax is telling php to run strtoupper on the string '$1' (which does nothing) and then pass that in as a replacement string to use for ALL matches made. Which would give you the exact same output as input.
Try this instead:
<?php
preg_replace_callback(
'/(_([a-z]{1}))/',
create_function(
// single quotes are essential here,
// or alternative escape all $ as \$
'$matches',
'return ucfirst($matches[0]);'
),
$subject
);
?>
Upvotes: 1
Reputation: 39197
Try adding letter "e" (meaning eval) as modifier to your regular expression.
$result = preg_replace("/(_([a-z]{1}))/e" , "strtoupper(\\1)" , $subject);
Upvotes: 1