I am trying to convert a string e.g. WhatAWonderfulDay
into a lowercase string where all uppercase characters are preceded with underscores e.g. what_a_wonderful_day
. Also, I am trying to make a reverse algorithm that translates let's say a_quick_fox
into AQuickFox
.
I am providing my implementation, though I know it's inefficient. Any ways to simplify these two operations?
// 1. WhatAWonderfulDay -> what_a_wonderful_day
$chars = str_split('WhatAWonderfulDay');
$result = "";
foreach($chars as $char) {
if (ctype_upper($char) && !empty($result))
$result .= "_"
$result .= $char;
}
echo $result;
// 2. a_quick_fox => AQuickFox
$chars = str_split('a_quick_fox');
$result = "";
$should_make_upper = true;
foreach($chars as $char) {
$result .= (should_make_upper) ? strtoupper($char) : $char;
$should_make_upper = false;
if ($char == "_")
$should_make_upper = true;
}
echo $result;