PHP Convert Camel Case String to underscore
Use PHP to convert the camel case string into an underscore-separated or other character separated.
Example
- Make the string's first character lowercase.
- Replace the uppercase letters in the string with specified characters.
- Make the string lowercase.
/**
* Convert Camel Case String to underscore-separated
* @param string $str The input string.
* @param string $separator Separator, the default is underscore
* @return string
*/
function camelCase2UnderScore($str, $separator = "_")
{
if (empty($str)) {
return $str;
}
$str = lcfirst($str);
$str = preg_replace("/[A-Z]/", $separator . "$0", $str);
return strtolower($str);
}
Use it
// Use underscore separator
echo camelCase2UnderScore("AbcXyzKLM");
// Use space separator
echo camelCase2UnderScore("AbcXyzKLM", " ");
Output:
abc_xyz_k_l_m
abc xyz k l m