If I had:
$string = \"PascalCase\";
I need
\"pascal_case\"
Does PHP offer a function for this purpose?>
Laravel 5.6 provides a very simple way of doing this:
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter
* @return string
*/
public static function snake($value, $delimiter = '_'): string
{
if (!ctype_lower($value)) {
$value = strtolower(preg_replace('/(.)(?=[A-Z])/u', '$1'.$delimiter, $value));
}
return $value;
}
What it does: if it sees that there is at least one capital letter in the given string, it uses a positive lookahead to search for any character (.
) followed by a capital letter ((?=[A-Z])
). It then replaces the found character with it's value followed by the separactor _
.