Table of contents

PHP Convert Camel Case String to underscore

PHP Jun 18, 2021 Viewed 4K Comments 0

Use PHP to convert the camel case string into an underscore-separated or other character separated.

Example

  1. Make the string's first character lowercase.
  2. Replace the uppercase letters in the string with specified characters.
  3. 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
Updated Jun 18, 2021