Current Location: Home> Latest Articles> How to Convert Hyphens to CamelCase in PHP

How to Convert Hyphens to CamelCase in PHP

gitbox 2025-06-16

1. What is CamelCase?

CamelCase is a naming convention in which the first word begins with a lowercase letter, and every subsequent word starts with an uppercase letter. This creates a name that resembles the hump of a camel. For example: camelCase.

2. Why Convert Hyphens to CamelCase?

In PHP, when a variable name contains a hyphen (`-`), you need to wrap the name in curly braces when using it, like so:

$stu_id = $student->{'stu-id'};

However, if you convert the hyphen to camelCase, you can directly access the property with a dot:

$stu_id = $student->stuId;

This approach makes the code more concise and easier to read.

3. Methods to Convert Hyphens to CamelCase in PHP

3.1 Using the preg_replace Function

You can use the `preg_replace` function with a regular expression to convert hyphens to camelCase. Here’s an example:


$str = 'student-name';
$str = preg_replace_callback('/-(\w)/', function($matches) {
    return strtoupper($matches[1]);
}, $str);
echo $str;  // Outputs studentName

This code uses the `preg_replace_callback` function to replace the hyphen and convert the following character to uppercase, thus achieving camelCase.

3.2 Using the str_replace Function

Another method is to use the `str_replace` function. First, replace the hyphen with a space, then capitalize the first letter of each word, and finally remove the spaces. Here’s an example:


$str = 'student-name';
$str = str_replace('-', ' ', $str);
$str = ucwords($str);
$str = str_replace(' ', '', $str);
echo $str;  // Outputs studentName

This code replaces the hyphens with spaces, uses `ucwords` to capitalize the first letter of each word, and then removes the spaces.

3.3 Using the Symfony String Component

The Symfony String Component offers a `camelize` method that makes it easy to convert hyphens to camelCase. Here’s an example:


use Symfony\Component\String\Inflector\EnglishInflector;
$inflector = new EnglishInflector();
$str = 'student-name';
$str = $inflector->camelize($str);
echo $str;  // Outputs studentName

In this code, we import the `EnglishInflector` class from `Symfony\Component\String\Inflector`, create an instance of `EnglishInflector`, and use its `camelize` method to perform the conversion.

4. Summary

There are several ways to convert hyphens to camelCase in PHP, including using `preg_replace`, `str_replace`, and the Symfony String Component. Depending on your specific needs, you can choose the most suitable method to improve the readability and maintainability of your code.