Last active
March 20, 2024 13:15
-
-
Save prasanth-j/783d355c7f8ebda450759de0872ef881 to your computer and use it in GitHub Desktop.
Helper to convert PascalCase strings or arrays of strings into snake_case format
This file contains 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 | |
/** | |
* Convert PascalCase string or array values to snake_case. | |
* | |
* @param array|string $input | |
* @return array|string | |
*/ | |
function pascalToSnakeCase(array|string $input): array|string | |
{ | |
// If the input is an array, recursively call this function for each element | |
if (is_array($input)) { | |
return array_map('pascalToSnakeCase', $input); | |
} | |
// Convert the input string from PascalCase to snake_case | |
return strtolower(preg_replace('/(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])/', '_$1', $input)); | |
} | |
// Example usage | |
$input = [ | |
'HelloWorld', | |
'ANOTHERExampleString', | |
['NestedStringOne', 'NESTEDStringTwo'], | |
['NestedStringThree', 'NestedStringFour'] | |
]; | |
$output = pascalToSnakeCase($input); | |
print_r($output); | |
// Output | |
Array | |
( | |
[0] => hello_world | |
[1] => another_example_string | |
[2] => Array | |
( | |
[0] => nested_string_one | |
[1] => nested_string_two | |
) | |
[3] => Array | |
( | |
[0] => nested_string_three | |
[1] => nested_string_four | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment