Laravel String Helpers

laravel-string-helpers

In addition to all of the common functionality we’ve come to know and love in Laravel such as routing, mail, file storage, middleware, authentication, and more, Laravel also provides some pretty cool helper functions to make common tasks easier. In this episode we’ll take a look at some of the string helpers that are included with Laravel and test them out to see how they work. Let’s check it out now.


camel_case()

First we’ll check out the camel_case() function that accepts a string, and then converts it to camel case. For example:

$camelfied = camel_case('this-is_a_-string');

echo $camelfied;

// thisIsAString

This is pretty cool, let’s see how it works. In the helpers.php file we find the code that references this function. Here it is:


if (! function_exists('camel_case')) {
    /**
     * Convert a value to camel case.
     *
     * @param  string  $value
     * @return string
     */
    function camel_case($value)
    {
        return Str::camel($value);
    }
}

We can see that it is calling on a static method of camel, so let’s go see how that works. In the Str class we find it here:


public static function camel($value)
    {
        if (isset(static::$camelCache[$value])) {
            return static::$camelCache[$value];
        }

        return static::$camelCache[$value] = lcfirst(static::studly($value));
    }

Interesting. First, it looks like the value is converted to studly case, then that result is run through the lcfirst function making the first character lowercase. This studly function is part of this same class so let’s have a look at how that works.


    public static function studly($value)
    {
        $key = $value;

        if (isset(static::$studlyCache[$key])) {
            return static::$studlyCache[$key];
        }

        $value = ucwords(str_replace(['-', '_'], ' ', $value));

        return static::$studlyCache[$key] = str_replace(' ', '', $value);
    }

So we can see that first off, the str_replace function is used to look for any hyphen or underscore characters in the string, and replace them with a blank space. Once this is complete, the ucwords function is applied creating a string like so:

$value = 'this-is_a_-string';

echo ucwords(str_replace(['-', '_'], ' ', $value));

// This Is A String

This result is once again put through the str_replace function and any blank spaces are removed from the string.

$value = 'This Is A String';

echo str_replace(' ', '', $value);

//  ThisIsAString

Finally, the lcfirst function is applied to this result in the public static function camel, resulting in our camel case string, thisIsAString.


class_basename()

Next up is the class_basename() function which gives you the base class of a namespaced representation of the class. For example:


$basename = class_basename('App\Http\Requests');

echo $basename;

//  Requests

Let’s see how it works. Again in the helpers.php file we find the following.

if (! function_exists('class_basename')) {
    /**
     * Get the class "basename" of the given object / class.
     *
     * @param  string|object  $class
     * @return string
     */
    function class_basename($class)
    {
        $class = is_object($class) ? get_class($class) : $class;

        return basename(str_replace('\\', '/', $class));
    }
}

The class_basename() function makes use of the built in PHP functions is_object() and get_class(), along with str_replace().


e()

Moving along and we come to the e() helper function, which makes it a whole lot easier to make use of the htmlentities function in PHP. Let’s test it out now:


$html = '<div class="boo">Technology</div>';

echo e($html);

//  <div class="boo">Technology</div>

Here is the function we find in the helpers.php file:

if (! function_exists('e')) {
    /**
     * Escape HTML entities in a string.
     *
     * @param  \Illuminate\Contracts\Support\Htmlable|string  $value
     * @return string
     */
    function e($value)
    {
        if ($value instanceof Htmlable) {
            return $value->toHtml();
        }

        return htmlentities($value, ENT_QUOTES, 'UTF-8', false);
    }
}

ends_with()

The ends_with() function checks a string to see if it ends with a particular value. Let’s try it out.


$string = 'God Bless America';

echo ends_with($string, 'America');

// 1 or true

The ends_with() function defers to the Str::endsWith in helpers.php, which defers to endsWith in the Str.php class file. This function in turn relies on the static substr function. Here are those snippets of code.

helpers.php


if (! function_exists('ends_with')) {
    /**
     * Determine if a given string ends with a given substring.
     *
     * @param  string  $haystack
     * @param  string|array  $needles
     * @return bool
     */
    function ends_with($haystack, $needles)
    {
        return Str::endsWith($haystack, $needles);
    }
}

Str.php


public static function endsWith($haystack, $needles)
{
    foreach ((array) $needles as $needle) {
        if ((string) $needle === static::substr($haystack, -static::length($needle))) {
            return true;
        }
    }

    return false;
}

//--------------------------//

public static function substr($string, $start, $length = null)
{
    return mb_substr($string, $start, $length, 'UTF-8');
}

We can see that this call to substr is actually a wrapper around the mb_substr() function. This thread at stack overflow gives us a good idea of the difference between the two.


snake_case()

This function takes a string and turns it into snake case. Let’s try it on the string we initially turned into a camel case. Recall we turned this-is_a_-string into thisIsAString using the camel_case() function. Let’s now put that result through the snake_case() function.


$string = 'thisIsAString';

echo snake_case($string);

// this_is_a_string

Upon inspecting the code, we found that you can also pass a second parameter to create your own version of the snake case. You can even do a umadbro emoji like so:


$string = 'thisIsAString';

echo snake_case($string, '¯\_(ツ)_/¯');

// this¯\_(ツ)_/¯is¯\_(ツ)_/¯a¯\_(ツ)_/¯string

This is really cool! The snake_case() is actually fairly involved in how it works making use of regular expressions to make the magic happen.


str_limit()

This function is very handy for when you want to show a block of text, such as in a card based layout, where all blocks of text are the same length so that the display is uniform. Basically, you pass this function a string of text as the first parameter and the number of characters you would like to display as the second argument. Here is an example:


$real_long_string = 'supercalifragilisticexpialidocious';
    
echo str_limit($real_long_string, 5);

//  super...

starts_with()

The starts_with() function can be used to check if a string starts with a given value.


$thestring = 'Ready. Set. Go!';

echo starts_with($thestring, 'Ready');

// 1 or true

str_contains()

Finding a value in a string is such a common task in PHP and many times we make use of strpos to complete this. Think of str_contains() as a more robust version of strpos() with an easier to reason about naming convention. Let’s see it in action here:


$stringvalue = 'Oh say can you see, by the dawn\'s early light';

echo str_contains($stringvalue, 'see');

//  1 or true

You can also check if the string contains multiple values using an array like so:


echo str_contains($stringvalue, ['see', 'light', 'Oh']);

//  1 or true

str_finish()

The str_finish() function acts like a string concatenator of sorts by adding a value to the end of the string. Here is our test of str_finish()


$string = 'Bae, can you do me a favor';

echo str_finish($string, ' - RIGHT NOW!');

//  Bae, can you do me a favor - RIGHT NOW!

str_is()

This function can be used to test for the occurrence of a pattern in a string, and you can use one or more wildcards for the pattern. Here are a few examples.

$string = 'Here we have a pattern';

echo str_is('*we*', $string);
//  1 or true

echo str_is('*pattern', $string);
//  1 or true

echo str_is('Here*', $string);
//  1 or true

echo str_is('joker', $string);
//  0 or false

str_plural()

The str_plural() function takes a word, and returns the plural form of it.


echo str_plural('Truck');
//  Trucks

echo str_plural('House');
//  Houses

str_singular()

In addition to being able to pluralize a word, we can convert back to the singular with the str_singular() function. Let’s try it out.


echo str_singular('Children');
//  Child

str_random()

If you need to generate a random string with a specific length, this is the function to do it. Here we are generating a random string 30 characters in length.


echo str_random(30);
//  6ypXOYMTHcze0AhM6xJRRtzOD31UTZ

str_slug()

The str_slug() function is perfect to sluggify any string. For example:


echo str_slug('Soon this string will be sluggified');
//  soon-this-string-will-be-sluggified

studly_case()

The studly_case() function is used to apply a studly case to a string. This means each significant word begins with an uppercase letter, including the first letter of the string. Let’s see it work.


echo studly_case('we can_turn--this__to studly');
//  WeCanTurnThisToStudly

title_case()

Similar to the studly case scenario we just examined is the title_case() function which works in a similar way, but adds a space between the words. Turn any string into a title in a snap.


echo title_case('10 tips for working with strings');
//  10 Tips For Working With Strings

Laravel String Helpers Summary

In this tutorial we had a look at most of the string helper functions available for you to use in your Laravel project. These functions exist in the helpers.php file, and make use of the static methods found in the Str.php class. These types of functions that complete small and useful tasks are perfect for a static method implementation. Have a play with these helpers, maybe you’ll find a good use case for your own project.