Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Convert Dashes to CamelCase in PHP
In PHP, converting dashes to camelCase is a common requirement when working with naming conventions. This can be achieved using built-in string functions like ucwords() and str_replace().
Sample input − this-is-a-test-string
Sample output − thisIsATestString
Method 1: Using ucwords() with Space Replacement
This method works by replacing dashes with spaces, capitalizing words, then removing spaces ?
<?php
function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashToCamelCase('this-is-a-test-string');
echo "<br>";
echo dashToCamelCase('user-profile-data', true);
?>
thisIsATestString UserProfileData
Method 2: Using ucwords() with Delimiter (PHP 5.3+)
For PHP version 5.3 and above, ucwords() accepts a delimiter parameter, making the process more efficient ?
<?php
function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashToCamelCase('this-is-a-test-string');
echo "<br>";
echo dashToCamelCase('api-response-handler', true);
?>
thisIsATestString ApiResponseHandler
Key Points
- Use
lcfirst()instead ofstrtolower()to convert only the first character to lowercase - The second parameter controls whether the first character should be capitalized (PascalCase vs camelCase)
- Method 2 is more efficient as it directly processes dashes as delimiters
Conclusion
Both methods effectively convert dash-separated strings to camelCase. Use Method 2 for PHP 5.3+ as it's more direct and efficient than the space replacement approach.
Advertisements
