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;
Here is some simpel code that will get you started:
$string = "AQuickTest";
preg_match_all("/[A-Z]/",$string,$matches);
foreach($matches[0] as $match){
$string = str_replace($match,"_".strtolower($match),$string);
}
echo $string;
The result is: _a_quick_test
I got a working solution using some basic regex.
To add underscores to a piece of text, use:
function addUnderscores($chars) {
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_\\0', $chars));
}
echo addUnderscores('WhatAWonderfulDay'); // Outputs "what_a_wonderful_day"
To remove them, use
function removeUnderscores($chars) {
return preg_replace_callback('/^\w|_(\\w)/', function ($matches) {
return strtoupper((sizeof($matches)==2)?$matches[1]:$matches[0]);
}, $chars);
}
echo removeUnderscores('a_quick_fox'); // Outputs "AQuickFox"