2010-12-15 5 views
1

リンクにアンカータグを追加するスマートな変更がありますか? 例えば表示されますSmarty Modifier - URLをリンクに変換します。

$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

私はこの修飾子を作成し、かなりうまく動作するようです。私は最大の改善が正規表現にあると思う。

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

を'preg_replace_callback'関数からの直接の値です。これにより、余分な変数を設定する手間を省くことができます。 – RobertPitt

0

また、あなたは、Smartyの変数の修飾子 "regex_replaceのを" 使用することができます。

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

は、すべてのURLのためにその作品このソリューションを試してみてください(HTTPS、HTTPとWWW)あなただけ返すことができます

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

これはとても奇妙な解決策ですが、本当にうまくいきます:D – Erikas

関連する問題