How to usepreg_replace_callback() Function in PHP
Another approach is to use preg_replace_callback() function with a regular expression to match each word and capitalize the first letter.
<?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
WelcomeTow3wiki
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.
How to Convert String to Camelcase in PHP?
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.
Table of Content
- Using ucwords() and str_replace() Functions
- Using preg_replace_callback() Function
- Using ucwords() and strtr() Functions
Contact Us