camelCase to dash - two capitals next to each other

simPod picture simPod · May 9, 2012 · Viewed 8.5k times · Source

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

Answer

Mark Byers picture Mark Byers · May 9, 2012

Use a lookahead assertion:

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

See it working online: ideone