Smarty修改器 - 将网址转换为链接

时间:2010-12-15 16:50:31

标签: php smarty modifiers

是否有一个smarty修饰符可以为链接添加锚标记。 例如

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

{$mytext|link}

将显示,

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

3 个答案:

答案 0 :(得分:3)

我创建了这个修饰符,似乎工作得很好。我认为最大的改进可能是正则表达式。

<?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;
} 

?>

答案 1 :(得分:0)

您也可以使用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>"}

答案 2 :(得分:-3)

你必须写一个插件。

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