php convert to camelcase code example
Example 1: php uppercase each word
$upperCaseSentance=ucwords("i do not feel good");
Example 2: php function to convert string to camelcase
echo ucwords("hello world");
Example 3: php string underscore into camelcase
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
Example 4: php camelcase to snake case
function from_camel_case($input) {
$pattern = '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!';
preg_match_all($pattern, $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ?
strtolower($match) :
lcfirst($match);
}
return implode('_', $ret);
}
foreach ([
'simpleTest' => 'simple_test',
'easy' => 'easy',
'HTML' => 'html',
'simpleXML' => 'simple_xml',
'PDFLoad' => 'pdf_load',
'startMIDDLELast' => 'start_middle_last',
'AString' => 'a_string',
'Some4Numbers234' => 'some4_numbers234',
'TEST123String' => 'test123_string',
] as $test => $result) {
$output = from_camel_case($test);
if ($output === $result) {
echo "Pass: $test => $result\n";
} else {
echo "Fail: $test => $result [$output]\n";
}
}