Regex Learnup from the Back of a Car

This past Thursday, one of my coworkers at Automattic gave a regex presentation from the back of a rental car. At one point, a nearby car’s alarm went off and everyone on the presentation heard the siren.

I was so amused by this, that I had to take a screenshot. In the picture, you’ll notice a headrest to the left of Dennis Snell’s face.

I wanted to share the screenshot because I felt it captured a bit of what the culture at Automattic is like. In a company where employees are allowed to work when and where they want, there’s bound to be a few moments like this. And while this is the first time I’ve been on a video call with someone in the back of a car, it is not the first time one of my coworkers has been in an interesting location.

If you find this exciting, why don’t you come work with us?

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.

h1,
h2,
h3,
h4,
h5,
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

Continue reading “Regular Expression Example: Wrapping the Second through Last Words in a Span Element”