#40: Rearranging a Table

Let's look at several utilities that use regular expressions. For a more complex example, let's say that you have a bunch of entries in an HTML table that looks like this:

<tr><td>last_name, first_name</td>
<td>address</td>
<td>phone number</td>
</tr>

Now assume that your boss just can't leave well enough alone and insists that you change it to this format:

<tr><td>first_name</td>
<td>last_name</td>
<td>address</td>
<td>phone number</td>
</tr>

You can do this in one fell swoop with backreferencing:

$table = preg_replace('/<td>([^<]*),\s*([^<]*)<\/td>/',
                      '<td>$1</td>' . "\n" . '<td>$2</td>',
                      $/table);

A bit of explanation is necessary. I split the arguments into three lines because they're easier to read that way. Notice that ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.