Convert string with dashes to camelCase

Convert string with dashes to camelCase

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Convert string with dashes to camelCase

Transforming a kebab-case string like this-is-a-string into camelCase (thisIsAString) is a frequent requirement when parsing configuration files, normalizing user input, or interacting with APIs that enforce specific naming conventions. The goal is straightforward: split the string at every hyphen, capitalize the subsequent words, and remove the separators. However, achieving this cleanly requires handling edge cases like leading capitalization preferences and empty segments.

Core Logic Implementation

The most robust approach involves splitting the input string by the delimiter, mapping over the resulting array to capitalize each segment, and then rejoining them. In PHP, you can achieve this using preg_split for flexible delimiter handling or a simple explode if the format is strictly hyphen-separated.

Here is a complete implementation that addresses the specific requirement in your source material:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    // Split the string by hyphens. preg_split handles consecutive delimiters gracefully.
    $segments = preg_split('/-+/', trim($string), -1, PREG_SPLIT_NO_EMPTY);

    // Map over segments to capitalize the first letter of each word.
    $camelCaseSegments = array_map(function ($segment) {
        return ucfirst(strtolower($segment));
    }, $segments);

    // If the user wants the very first character of the entire string to be lowercase,
    // we modify the first element back to lower case.
    if (!$capitalizeFirstCharacter && !empty($camelCaseSegments)) {
        $camelCaseSegments[0] = lcfirst($camelCaseSegments[0]);
    }

    return implode('', $camelCaseSegments);
}

This function handles the core transformation by first normalizing all characters to lowercase using strtolower. This prevents issues where mixed-case input like MiXeD-cAsE results in incorrect output. The preg_split with the -+ pattern ensures that multiple consecutive dashes (e.g., foo--bar) are treated as a single separator, preventing empty strings from appearing in the final array.

Handling Edge Cases and Configuration

One of the trickiest aspects of this conversion is the treatment of the first character. Standard camelCase definitions often dictate that the first letter should be lowercase (e.g., thisIsAString), while PascalCase requires the first letter to be uppercase (ThisIsAString). The parameter $capitalizeFirstCharacter in the example above allows callers to toggle this behavior without rewriting logic.

However, consider strings containing leading or trailing whitespace. If you pass " my-string ", a naive split might include spaces as part of the segments. Wrapping the split operation with trim() is essential to ensure clean output. Additionally, using PREG_SPLIT_NO_EMPTY in preg_split is a critical safety measure; without it, multiple hyphens at the start or end of the string would generate empty strings that pass through the ucfirst filter unchanged, resulting in artifacts like _thisIsAString.

When to Use This Pattern

This utility function is particularly useful when building data normalizers for JSON payloads or when processing environment variables exported in shell scripts. If you are working within a Laravel application, you might find this logic beneficial inside service classes that handle request validation. For instance, if an API expects camelCase but your database stores kebab-case keys, a dedicated transformer can bridge the gap before hydration.

For larger projects, consider extracting this logic into a utility class or registering it as a helper method within your AppServiceProvider. This keeps your core domain logic clean and ensures consistent naming conventions across different parts of the codebase. If you need to handle more complex transformations, such as converting snake_case to camelCase simultaneously, you would simply change the regex delimiter from - to _.

Ultimately, the choice between using a raw string manipulation approach or leveraging a library like illuminate/support/Str depends on your project's dependencies. Laravel provides helper methods that abstract these patterns, but understanding the underlying mechanics—as shown above—ensures you can debug issues when the built-in helpers don't cover your specific edge cases.

Our network