Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A macro to produce AP-style headings in Laravel

If you’re a journalist or a writer, you might be familiar with the AP Stylebook commonly known as “AP-style”. It’s a writing style guide for journalists and it’s widely used in the United States.

The AP Stylebook has a set of rules for capitalization, abbreviation, spelling, numerals, punctuation, and usage. And it also has a set of rules for writing headlines.

For instance, the AP Stylebook says that you should use the title case for headlines. And it also says that you should capitalize the first and last word in a headline. You should also capitalize all the other words except for articles, conjunctions, and prepositions.

So, for instance, if you have a headline like so,

this is a headline

The AP-style headline would be,

This is a Headline

Now, if you’re using Laravel, you can easily convert a string to a title case using the Str::title() method. But, it doesn’t do it according to the AP Stylebook. And that’s where you can use this handy string macro shared by Jeffrey Way recently.

Str::macro('heading', function (string $string) {
    return collect(explode(' ', $string))->map(function($word, $index) {
        $word = strtolower($word);

        $exceptions = [
            'of', 'a', 'the', 'and', 'an', 'or', 'nor', 
            'but', 'is', 'if', 'then', 'else', 'when', 'at', 
            'from', 'by', 'on', 'off', 'for', 'in', 'out', 
            'over', 'to', 'into', 'with'
        ];

        return ($index === 0 || !in_array($word, $exceptions)) 
                    ? first($word)
                    : $word;
    })->implode(' ');
});

Here’s how you can use it.

$blogTitle = Str::heading(
    'the quick brown fox jumps over the lazy dog'
);

echo $blogTitle;

// output: The Quick Brown Fox Jumps over the Lazy Dog

As you can tell, it produces a string according to the AP Stylebook rules.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?