PHP में dash-separated strings (kebab-case) को camelCase में बदलने के सरल और कुशल तरीके।
विधि 1: ucwords() के साथ (PHP 5.3+)
function dashToCamelCase($string, $capitalizeFirst = false) {
// Dashes को spaces में बदलें, फिर ucwords, फिर spaces हटाएं
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirst) {
$str[0] = strtolower($str[0]); // पहला अक्षर lowercase
}
return $str;
}
// उपयोग
echo dashToCamelCase('this-is-a-test-string'); // thisIsATestString
echo dashToCamelCase('this-is-a-test-string', true); // ThisIsATestString
विधि 2: ucwords() में Delimiter पैरामीटर (PHP 5.4.32+, 5.5.16+)
function dashToCamelCase($string, $capitalizeFirst = false) {
// ucwords सीधे delimiter स्वीकार करता है
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirst) {
$str = lcfirst($str); // strtolower($str[0]) से बेहतर
}
return $str;
}
विधि 3: Regex के साथ (एक लाइनर)
function dashToCamelCase($string, $capitalizeFirst = false) {
$callback = function($matches) {
return strtoupper($matches[1]);
};
$str = preg_replace_callback('/-([a-z])/i', $callback, $string);
return $capitalizeFirst ? ucfirst($str) : lcfirst($str);
}
विधि 4: explode + array_map (स्पष्ट)
function dashToCamelCase($string, $capitalizeFirst = false) {
$parts = explode('-', $string);
$first = array_shift($parts);
$parts = array_map('ucfirst', $parts);
$result = $capitalizeFirst ? ucfirst($first) : lcfirst($first);
$result .= implode('', $parts);
return $result;
}
परीक्षण मामले
| Input | Output (lower first) | Output (upper first) |
|---|---|---|
hello-world | helloWorld | HelloWorld |
this-is-a-test | thisIsATest | ThisIsATest |
single | single | Single |
UPPER-CASE | upperCase | UpperCase |
with123-numbers | with123Numbers | With123Numbers |
व्यावहारिक उपयोग: CSS Property Names
$cssProps = ['background-color', 'font-size', 'margin-top', 'z-index'];
$jsProps = array_map('dashToCamelCase', $cssProps);
// Result: ['backgroundColor', 'fontSize', 'marginTop', 'zIndex']