Skip to content

Instantly share code, notes, and snippets.

@justjkk
Created November 28, 2011 21:06
Show Gist options
  • Save justjkk/1402061 to your computer and use it in GitHub Desktop.
Save justjkk/1402061 to your computer and use it in GitHub Desktop.
CamelCase to Title Case PHP Regex
<?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();
?>
@krisanalfa
Copy link

AWESOME!!!

@chasen
Copy link

chasen commented May 13, 2015

Thanks!

@JohnLukeBentley
Copy link

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);

@tahirafridi
Copy link

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.

@JohnLukeBentley
Copy link

@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