2011-07-07 49 views
-1

我需要一些幫助。我有一個顯示關鍵字 「標籤」 一節:使用`str_replace`創建鏈接

<?=str_replace(",",",",$line["m_tags"])?> 

上面的代碼看起來像這樣

標籤:關鍵詞1,關鍵詞,KEYWORD3

所有我想要做的是否有每個個人KEYWORD是一個超鏈接來鏈接回主頁面。 任何幫助,將不勝感激。

+3

你的替換沒有意義....你自己替換''''('str-replace'標籤不需要btw)。鏈接應該如何? –

+0

您沒有提供關於您網站的數據結構的信息 - 我們可以從哪裏獲取鏈接。正如@Felix所說,str_replace完全是多餘的。 –

回答

2

您發佈的代碼什麼都不做,它會用,代替,。 你可以用正則表達式做到這一點,但這裏是一個不同的方法:

$output = ''; 
$tmp = explode(",",$line['m_tags']); /* convert to array */ 

foreach($tmp as $tag) 
    $output .= '<a href="index.php">'.$tag.'</a>, '; /* put link in output */ 

echo substr($output,0,-2); /* echo output without the last , */ 

較短的替代,因爲菲利克斯克林指出:

$tmp = explode(",",$line['m_tags']); /* convert to array */ 

foreach($tmp as $key => $tag) 
    $tmp[$key] = '<a href="index.php">'.$tag.'</a>'; /* put link back in tmp */ 

echo implode(",",$tmp); 
+1

你更快:) –

+0

更好:將字符串放回'$ tmp'數組並使用'implode'。 –

+0

Kokos非常感謝你的時間,並幫助我找到了我想要的東西。 – John

1

要麼這應該工作:

Tags: <? 
// php5.3 
$tags=explode(",", $line["m_tags"]); 
$tags = array_map(function($tag){ 
    return "<a href='http://www.yoursite.com/?tag=$tag'>$tag</a>"; 
}, $tags); 
echo implode(", ", $tags); 
?> 
+0

由四個空格縮進代碼...並歡迎來到SO :) *編輯:*哦,不,我已經編輯它... –

+0

謝謝,新手在工作:)好吧,幸運的是,這不是Python – lcapra

+0

只使用反引號\'for內聯代碼;) –

0

這是我可能會這樣做的。

$str = "KEYWORD1,KEYWORD2,KEYWORD3"; 
$keywords = explode(',', $str); 
$links = array(); 
foreach($keywords as $keyword) { 
    $links[] = "<a href='home'>$keyword</a>"; 
} 

echo implode(', ', $links);