Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jonathan1's avatar

retaining case when using str_slug()

I have a title like this, "This or That But Not There" as an example.

I'd like the slug to be converted to..

"This-or-That-But-Not-There" instead of the default all lowercase.

I tried str_slug($str) with the above, but it gives me "this-or-that-but-not-there"

Is there a way to retain the capitalization of the string when converting to URL?

0 likes
2 replies
jonathan1's avatar

Thanks for the suggestion, that worked beautifully.

I added a helper to app/Http/helpers.php and added to composer.json, then ran composer dump-autoload

here's the helper I added

    function tracker_slug($title, $separator = '-', $language = 'en')
    {
        // Convert all dashes/underscores into separator
        $flip = $separator == '-' ? '_' : '-';
        $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
        // Replace @ with the word 'at'
        $title = str_replace('@', $separator.'at'.$separator, $title);
        // Remove all characters that are not the separator, letters, numbers, or whitespace.
        $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', $title);
        // Replace all separator characters and whitespace by a single separator
        $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
        return trim($title, $separator);
    }

Followed this for adding the helper.php: https://laracasts.com/discuss/channels/general-discussion/best-practices-for-custom-helpers-on-laravel-5?page=1

Please or to participate in this conversation.