Issue
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.
Solution
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);
Answered By - David Stockton Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.