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:

//returns a span with the class specified around the word specified within a phrase
//@text (str) is the text to look within
//@nth (mixed) is the word to style, either an integer or "first" or "last"
//@class is the span class name to apply.
function style_nth_word($text, $nth="last", $class="nth-word"){
   $words = str_word_count(htmlspecialchars_decode(strip_tags($text)),1,"’'()");
   $count = count($words);

   if($nth == "first"){
     $get = 0;
   }elseif($nth=="last"){
     $get = $count-1;
   }elseif(is_numeric($nth) && $nth > 0){
     if($nth > $count){
        $get = $count-1;
     }else{
        $get = $nth - 1;
   }
 }else{
   return false;
 }

  $words[$get]=('<span class="'.$class.' word-'.($get+1).'">'.$words[$get].'</span>');

return(implode(" ", $words));
}

Usage:

General Usage

<?php echo style_nth_word("Stand Up Paddleboard Rentals", "last"));?>

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

<?php echo apply_filters('the_title',style_nth_word($post--->post_title, "last"));?>

Output:

Stand Up Paddleboard <span class="nth-word word-4">Rentals</span>