Tuesday, January 29, 2008

PHP, On Its Way To Being Scheme

I was solving the following problem in PHP:

Search through a string and replace all cases of URLs with HTML anchor tags. If the URL is greater than 50 characters, then make the display part of the anchor tag abbreviated.

I knew that preg_replace was probably the key to solving this problem. But I was positively giddy to see that PHP offered me preg_replace_callback, which would allow me to conveniently perform the transformation I was looking for. I ended up with the following solution:

 function format_url($matches) {
    $url = $matches[1];
    $display = strlen($url) > 50 ? 
     substr($url, 0, 40) . "..." . substr($url, -10, 10) : 
    return "$display";
 $text = preg_replace_callback("|(https?://[^ \n\r\t]+)|", "format_url", $text);

What struck me was how Scheme-like this solution was. And it's not just preg_replace_callback that offers this Scheme'ish feeling. PHP also offers array_map and array_filter, which are standard building blocks in the Lisp and Scheme world.

What's missing from PHP are first class functions. PHP offers create_function which is used to create an anonymous function. Unfortunately, the body of the function is written as a string, which is clunky, to say the least. Add to this that a callback needs to be passed around as a string, and you appreciate that PHP has some room to grow in this area.

I have to say, I feel like I'm watching Greenspun's Tenth Rule in action.

No comments:

Post a Comment