Search code examples
phpregexcamelcasingkebab-case

camelCase to dash - two capitals next to each other


I'm using this function to convert CamelCase to dashed string:

function camel2dashed($className) {
    return strtolower(preg_replace('/([^A-Z-])([A-Z])/', '$1-$2', $className));
}

it kinda works but theres problem when I have for ex. this string: getADog. It returns get-adog but I want get-a-dog

how should I change my code? Thanks


Solution

  • Use a lookahead assertion:

    function camel2dashed($className) {
        return strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $className));
    }
    

    See it working online: ideone