Widont for the Zend Framework – automatically remedies text widows

Posted on September 10th, 2008 by Luke Visinoni

When I came across Shaun Inman’s clever Widon’t wordpress plug-in this morning, I thought to myself “What the heck is an unwanted browser window?”, as I read on I realized it said
“widow”. If you have never heard of a widow, you’ve likely never worked in the print industry. On the web, most of us have gotten rather sloppy when it comes to good typography, but in our defense, our medium doesn’t really lend itself to good practices. A widow is a lone word on the end of a header or paragraph. The header of this post would have had a widow, had I not used Shaun’s plugin (for a better explanation of a widow, refer to this article).

Since I’ve been using the Zend Framework so much lately, I figured why not add this functionality into it? Here’s a view helper to do just that. Enjoy!

class Zend_View_Helper_Widont {
 
    public $view;
 
    public function widont($str = '', $escape = false) {
 
        if ($escape) $str = $this->view->escape($str);
        return preg_replace( '|([^\s])\s+([^\s]+)\s*$|', '$1 $2', $str);
 
    }
 
    public function setView($view) {
 
        $this->view = $view;
 
    }
 
}

Refer to the Zend Framework’s view helper documentation if you don’t know how to install view helpers.

To use this helper, call $this->widont($str) from inside of a view. If you pass a true value as the second argument, the string will be escaped before being output.

2 Responses to “Widont for the Zend Framework – automatically remedies text widows”

  1. Definitely a practical helper. I added it to the Kohana Framework some time ago.

    The only thing that I am wondering about is why you are using a regular expression? Aren’t strrpos() and substr() slightly faster?

    On a sidenote, matching non-space characters can be done with \S which is shorter than [^\s].

  2. I am using the regular expression Shaun is using in the newest version of widont for wordpress. I’ll post a regex-less version in a minute. I completely forgot about \S. I’ll add it in, thanks!