Does Twig include a filter for auto-linking text?

If you are using twig inside of Symfony2, there's a bundle for that: https://github.com/liip/LiipUrlAutoConverterBundle

If you're using it outside of Symfony2, you could submit a PR to them in order to decouple the bundle and the twig extension!


the function doesn't exist in twig, but you can even add your own extensions to Twig :

class AutoLinkTwigExtension extends \Twig_Extension
{

    public function getFilters()
    {
        return array('auto_link_text' => new \Twig_Filter_Method($this, 'auto_link_text', array('is_safe' => array('html'))),
        );
    }

    public function getName()
    {
        return "auto_link_twig_extension";
    }

    static public function auto_link_text($string)
    {

        $regexp = "/(<a.*?>)?(https?)?(:\/\/)?(\w+\.)?(\w+)\.(\w+)(<\/a.*?>)?/i";
        $anchorMarkup = "<a href=\"%s://%s\" target=\"_blank\" >%s</a>";

        preg_match_all($regexp, $string, $matches, \PREG_SET_ORDER);

        foreach ($matches as $match) {
            if (empty($match[1]) && empty($match[7])) {
                $http = $match[2]?$match[2]:'http';
                $replace = sprintf($anchorMarkup, $http, $match[0], $match[0]);
                $string = str_replace($match[0], $replace, $string);
            }
        }

        return $string;
    }
}

The other listed "answer" is a little out of date and has issues. This one will work in the latest versions of Symfony and has less issues

class AutoLinkTwigExtension extends AbstractExtension
{
    public function getFilters()
    {
        return [new TwigFilter('auto_link', [$this, 'autoLink'], [
            'pre_escape'=>'html',
            'is_safe' => ['html']])];
    }

    static public function autoLink($string)
    {
        $pattern = "/http[s]?:\/\/[a-zA-Z0-9.\-\/?#=&]+/";
        $replacement = "<a href=\"$0\" target=\"_blank\">$0</a>";
        $string = preg_replace($pattern, $replacement, $string);
        return $string;
    }
}

Tags:

Twig

Symfony