Regular Expression Example: Wrapping the Second through Last Words in a Span Element

For the past week, I have been working on a website for an emergency medical services association. To fit the client’s wishes, the design called for the first word in titles to be blue followed by all other words being red.

I do not know a way to do this with just HTML, so I decided that I would wrap the second through the last words in a span  element. Then I could add some LESS like this to achieve the color effect I wanted.

h6 {
color: blue;

span {
color: red;

But, how do I get the span element in the titles?

Using Regular Expressions to Add the Span

Regular expressions are a very powerful feature of many languages. They allow us to create very complex rules to match phrases in code, words, etc. We can also “capture” parts of these rules, which will prove useful in this example!

Here is a PHP function with a regular expression example that takes a title and wraps the second through last words in a span  element.

function span_the_title( $title ) {
    return preg_replace( '#(S+)s(.+)#', '$1 <span>$2</span>', $title );

Let’s break this down. Notice that I am passing $title in to the function. This is the title that we will actually be filtering in the regular expression. Now take a look at the preg_replace() function. This function takes the following arguments:

  1. A regular expression that is the pattern to search for.
  2. A string to replace matched expressions with. Notice how I used $1 and $2 in the second argument above. This is because I am referencing part of the matched regular expression from the first argument. More on this later.
  3. The third argument is the title, in this case, or really any string.

Let’s Break It Down

Read more