2010-12-15 71 views
1

是否有一個smarty修飾符會將鏈接添加錨定標記。 如Smarty Modifier - 將網址轉爲鏈接

$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 2011-02-10 18:02:43

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

嘗試這種解決方案的適用於所有的網址(https,HTTP和WWW)

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

這是很奇怪的解決方案,但它確實有效:D – Erikas 2017-08-12 14:45:54