Style Nth Word In a Phrase

The CSS Scenario

Recently my graphic designer used a nice styling on a client’s webpage headlines–all words in the headline were one color and the last word was a different color.

style-nth-word

It adds for a nice effect I think.

Of course, as the developer I’m the one who has the responsibility to bring that to life.

After a few quick searches on Google for phrases like,

  • CSS Style Nth Word
  • CSS style last word, CSS style first word
  • php style nth word, php style first word, php get first word
  • etc.

and getting results on how CSS doesn’t provide for this functionality–but does for just first letter–I quickly realized that I was going to have to roll my own.

Being in the midst of a big project, this is down and dirty code. There are likely faster or more elegant methods using regular expressions, but this gets the job done. I added in the ability to select a word by number or by specifying “first” or “last.” If you specify a word number that doesn’t exist (say a 4 word phrase is passed and you tell it to select the 6th word for instance), then just the last word is styled.

Enjoy, and please don’t hesitate to comment or send improvements my way.

The Code:

Usage:

General Usage

WordPress Page/Post Title Usage
(You’ll want to pass the unfiltered, or raw, post title. Otherwise formatting issues with punctuation can occur.)

Output:

Speak Your Mind

*