Open In App

How to Convert String to Camelcase in PHP?

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String containing spaces, the task is to Convert String to Camelcase in PHP. Converting a string to CamelCase is a common operation in PHP, especially when working with variable names or class names. CamelCase is a naming convention where the first letter of each word in a compound word is capitalized except for the initial word. In this article, we will cover all possible approaches to convert a string to CamelCase in PHP.

Approach 1: Using ucwords() and str_replace() Functions

One method to convert a string to CamelCase is by using the ucwords() function to capitalize the first letter of each word, and then using str_replace() to remove the spaces.

PHP
<?php 

function camelCase($string) {
    $string = str_replace(' ', '', 
        ucwords(str_replace(['-', '_'], 
        ' ', $string))
    );
  
    return $string;
}

// Driver Code
$str = 'welcome to geeks-for-geeks';
$camelCase = camelCase($str);
echo $camelCase;

?> 

Output
WelcomeToGeeksForGeeks 

Explanation:

  • First replace underscores and hyphens with spaces using str_replace() function.
  • Then capitalize the first letter of each word using ucwords() function.

Approach 2: Using preg_replace_callback() Function

Another approach is to use preg_replace_callback() function with a regular expression to match each word and capitalize the first letter.

PHP
<?php

function camelCase($string) {
    return preg_replace_callback('/(?:^|_| )(.?)/', 
        function($matches) {
            return strtoupper($matches[1]);
        }, $string);
}

// Driver Code
$str = 'welcome to geeks for geeks';
$camelCase = camelCase($str);
echo $camelCase;

?>

Output
WelcomeToGeeksForGeeks

Explanation:

  • The regular expression /(?:^|_)(.?)/ matches the beginning of the string or an underscore followed by any character.
  • The preg_replace_callback() function is used to apply a callback function to each match, converting the matched character to uppercase.

Approach 3: Using ucwords() and strtr() Functions

This approach uses strtr() functions to replace underscores with spaces, then use ucwords() to capitalize each word, and finally str_replace() to remove spaces.

PHP
<?php

function camelCase($string) {
    $string = ucwords(
        strtr($string, 
        ['_' => ' ', '-' => ' '])
    );
    
    $string = str_replace(' ', '', $string);
    
    return $string;
}

// Driver Code
$str = 'welcome to geeks for geeks';
$camelCase = camelCase($str);
echo $camelCase;

?>

Output
welcomeToGeeksForGeeks

Explanation:

  • strtr is used to replace underscores and hyphens with spaces.
  • Finally, we remove spaces and lowercase the first letter of the resulting string.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads