How can I camelcase a string in php

10,545

Solution 1

Have you considered using Laravel's built-in camel case functtion?

$camel = camel_case('foo_bar');

Full details can be found here:

https://laravel.com/docs/4.2/helpers#strings

Solution 2

So one possible solution that could be used is the following.

private function camelCase($string, $dontStrip = []){
    /*
     * This will take any dash or underscore turn it into a space, run ucwords against
     * it so it capitalizes the first letter in all words separated by a space then it
     * turns and deletes all spaces.
     */
    return lcfirst(str_replace(' ', '', ucwords(preg_replace('/^a-z0-9'.implode('',$dontStrip).']+/', ' ',$string))));
}

It's a single line of code wrapped by a function with a lot going on...

The breakdown

What is the dontStrip variable?

Simply put it is an array that should contain anything you don't want removed from the camelCasing.

What are you doing with that variable?

We are taking every element in the array and putting them into a single string.

Think of it as something like this:

function implode($glue, $array) {
    // This is a native PHP function, I just wanted to demonstrate how it might work.
    $string  = '';
    foreach($array as $element){
        $string .= $glue . $element;
    }
    return $string;
}

This way you're essentially gluing all your elements in your array together.

What's preg_replace, and what's it doing?

preg_replace is a function that uses a regular expression (also known as regex) to search for and then replace any values that it finds, which match the desired regex...

Explanation of the regex search

The regex used in the search above implodes your array $dontStrip onto a little bit a-z0-9 which just means any letter A to Z as well as numbers 0 to 9. The little ^ bit tells regex that it's looking for anything that isn't whatever comes after it. So in this case it's looking for any and all things that aren't in your array or a letter or number.

If you're new to regex and you want to mess around with it, regex101 is a great place to do it.

ucwords?

This can be most easily though of as upper case words. It will take any word (a word being any bit of characters separated by a space) and it will capitalize the first letter.

echo ucwords('hello, world!');

Will print `Hello, World!'

Okay I understand what preg_replace is, what str_replace?

str_replace is the smaller, less powerful but still very useful little brother/sister to preg_replace. By this I mean that it has a similar use. str_replace doesn't regex, but does use a literal string so whatever you type into the first parameter is exactly what it will look for.

Side note, it is worth mentioning for anyone considering only using preg_replace where str_replace would work just as well. str_replace has been noted to be benchmarked a bit faster than preg_replace on larger apps.

lcfirst What?

Since about PHP 5.3 we have been able to use the lcfirst function, which much like ucwords, it's just a text manipulation function. `lcfirst turns the first letter into it's lower case form.

echo lcfirst('HELLO, WORLD!');

Will print 'hELLO, WORLD!'

Results

All this in mind the camelCase function uses distinct non-alphanumeric characters as break points to turn a string to a camelCase string.

Solution 3

There's a general purpose open source library that contains a method that performs case convertions for several popular case formats. library is called TurboCommons, and the formatCase() method inside the StringUtils does camel case conversion.

https://github.com/edertone/TurboCommons

To use it, import the phar file to your project and:

use org\turbocommons\src\main\php\utils\StringUtils;

echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);

// will output 'sNakeCase'
Share:
10,545
Austin Kregel
Author by

Austin Kregel

I am a web developer, I work mostly with PHP, HTML/CSS/JS, VueJS, and Laravel; however, I have touched on various other languages like Python, and C/C++. I have done a good chunk of work with Java, and the Android SDK. I have been focusing heavily on the Laravel framework, for the past few years, but before that I would just use straight PHP (without a framework). While backend development might be my specialty I do enjoy doing some web design, and plain ol' desktop app work.

Updated on June 13, 2022

Comments

  • Austin Kregel
    Austin Kregel almost 2 years

    Is there a simple way I can have php camelcase a string for me? I am using the Laravel framework and I want to use some shorthand in a search feature.

    It would look something like the following...

    private function search(Array $for, Model $in){
        $results = [];
        foreach($for as $column => $value){
            $results[] = $in->{$this->camelCase($column)}($value)->get();
        }
        return $results;
    }
    

    Called like

    $this->search(['where-created_at' => '2015-25-12'], new Ticket);
    

    So the resulting call in the search function I would be using is

    $in->whereCreateAt('2015-25-12')->get();
    

    The only thing is I can't figure out is the camel casing...