Модификатор Smarty - превращайте URL-адреса в ссылки

Есть ли модификатор 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>

person andrew    schedule 15.12.2010    source источник


Ответы (4)


Я создал этот модификатор, вроде работает неплохо. Я думаю, что самое большое улучшение может быть в регулярном выражении.

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

?>
person andrew    schedule 16.12.2010
comment
Вы можете просто вернуть значение прямо из функции preg_replace_callback, это избавит вас от установки дополнительной переменной. - person RobertPitt; 10.02.2011

Попробуйте это решение, оно работает для всех URL-адресов (https, http и www).

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

Также вы можете использовать модификатор переменной Smarty "regex_replace":

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

Вам нужно будет написать плагин.

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

person profitphp    schedule 15.12.2010