<?php

class Am_View_Helper_Hyperlinks extends Zend_View_Helper_Abstract
{
    public function hyperlinks($string)
    {
        $pattern = '#
                (\[(.*?)]\()?
                    (
                        (https?://|www\.)(.*?)
                    )
                    (
                        ([>".?,)]{0,1}\.?(\s|$)) | (&(quot|gt);)
                    )
            #ix';
        return preg_replace_callback($pattern, function($m) {
            $label = Am_Html::escape($m[2] ?: $m[3]);
            $url = Am_Html::escape(substr($m[3], 0, 4) == 'www.' ? "http://{$m[3]}" : $m[3]);
            return '<a href="' . $url . '" target="_blank" rel="noreferrer">' . $label . '</a>' . ($m[2] ? preg_replace('/^\)/', '', $m[6]) : $m[6]);
        }, $string);
    }
}