Created
November 28, 2011 21:06
-
-
Save justjkk/1402061 to your computer and use it in GitHub Desktop.
CamelCase to Title Case PHP Regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function camelToTitle($camelStr) | |
{ | |
$intermediate = preg_replace('/(?!^)([[:upper:]][[:lower:]]+)/', | |
' $0', | |
$camelStr); | |
$titleStr = preg_replace('/(?!^)([[:lower:]])([[:upper:]])/', | |
'$1 $2', | |
$intermediate); | |
return $titleStr; | |
} | |
function testCamelToTitle() | |
{ | |
$testData = array( | |
'', | |
'sample', | |
'Sample', | |
'sampleStr', | |
'SampleStr', | |
'SomeIDWithNumb3rs', | |
'SomeID4Test', | |
'ABCPvtLtd', | |
'ABC', | |
); | |
foreach ($testData as $value) { | |
echo "'" . $value . "' => '" . camelToTitle($value) . "'\n"; | |
} | |
} | |
testCamelToTitle(); | |
?> |
Thanks!
Great function.
I was expecting each returned word to have an uppercased first letter. e.g.
'sample' => 'Sample'
'sampleStr' => 'Sample Str'
... so I changed (in my own function) the returning line to ...
return ucwords($titleStr);
Great function.
I was expecting each returned word to have an uppercased first letter. e.g.
'sample' => 'Sample' 'sampleStr' => 'Sample Str'
... so I changed (in my own function) the returning line to ...
return ucwords($titleStr);
Thanks for fixing it, this is what I noticed, by the way thanks for sharing the whole gist.
@tahirafridi you are welcome on the fix!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AWESOME!!!