andrew
andrew

Reputation: 5176

Smarty Modifier - Turn urls into links

Is there a smarty modifier that will add anchor tags to links. eg

$smarty->assign('mytext','This is my text with a http://www.link.com');

{$mytext|link}

which will display,

This is my text with a <a href='http://www.link.com'>http://www.link.com</a>

Upvotes: 1

Views: 5063

Answers (4)

Abderrazzak Talal
Abderrazzak Talal

Reputation: 43

Try this solution its works for all URLS (https, http and www)

{$customer.description|regex_replace:" @((([[:alnum:]]+)://|www\.)([^[:space:]]*)([[:alnum:]#?/&=]))@":
 " <a href=\"\\1\" target=\"_blank\" >\\1</a>"}

Upvotes: 1

Nekiy
Nekiy

Reputation: 1

Also you can use Smarty Variable Modifier "regex_replace":

{$variable|regex_replace:"/\b((https?):\/\/([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*))\b/i":"<a href='$1' target='_blank'>$3</a>"}

Upvotes: 0

andrew
andrew

Reputation: 5176

I created this modifier, seems to work pretty well. I think the biggest improvement could be to the regex.

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage PluginsModifier
 */

/**
 * Smarty link_urls plugin 
 * 
 * Type:     modifier<br>
 * Name:     link_urls<br>
 * Purpose:  performs a regex and replaces any url's with links containing themselves as the text
 * This could be improved by using a better regex.
 * And maybe it would be better for usability if the http:// was cut off the front?
 * @author Andrew
 * @return string 
 */

function smarty_modifier_link_urls($string)
{
    $linkedString = preg_replace_callback("/\b(https?):\/\/([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)\b/i",
                                create_function(
                                '$matches',
                                'return "<a href=\'".($matches[0])."\'>".($matches[0])."</a>";'
                                ),$string);

    return $linkedString;
} 

?>

Upvotes: 4

profitphp
profitphp

Reputation: 8354

You will have to write a plugin.

http://www.smarty.net/docsv2/en/

Upvotes: -3

Related Questions