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.
Geert De Deckere Says:
September 15th, 2008 at 7:40 am
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].
Luke Visinoni Says:
September 15th, 2008 at 8:00 am
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!