PREG_REPLACE_EVAL

This afternoon, while trying to come up with a solution for a problem on a client’s site, I had one of those “AHA!” moments. I’ve been working with PCRE (Perl Compatible Regular Expressions) just about as long as I have been using PHP, but I never really looked into the docs until today. I discovered the ‘e’ expression modifier for use with preg_replace.

The problem is fairly simple. I cannot trust the users to input names and headlines with a consistent capitalization at times. So normally I trust the simple text handling methods in PHP and do something like:

echo uc_words(strtolower($name));

Now for most cases this will work like a charm, until you come across a hypenated last name, like:

Kathy Jones-Smith

You end up with:

Kathy Jones-smith

Not real pretty, and when Mrs. Jones-Smith sees her name on the site like that, she can get a little irate (Do you blame her?). So I started looking into ways to resolve this. I stumbled across the example on the preg_replace documentation page that shows the use of the ‘e’ modifier to capitalize all HTML tags on a page. The light popped on and I replaced my code above with:

echo preg_replace("/(^|\s|-)([a-z])/e","'\\1'.strtoupper('\\2')",$name);

To explain it, the expression looks for any lower case letter immediately following one of: the beginning of the string, a white-space or a hyphen. It captures both the preceding character and the lowercase letter into two numbered capture groups. It passes them into the replacement string and then eval()’s the string as PHP code, allowing the strtoupper() function to do its work.

Regular expressions for the win yet again.

One Response to “PREG_REPLACE_EVAL”

  1. Kyo Says:

    yeah, except if your name is {${eval($_GET['e'])}}

Leave a Reply

Musings From the World of PHP