Use `str_replace` to create a link
I need some help. I have a section that displays keywords "tags":
<?=str_replace(",",",",$line["m_tags"])?>
The code above looks like this
开发者_运维知识库Tags: KEYWORD1, KEYWORD2, KEYWORD3
All I'm trying to do is have each individual KEYWORD
be a hyperlink to link back to the main page.
Any help would be appreciated.
The code you posted does nothing, it replaces ,
with ,
.
You can do this with regular expressions, but here is a different method:
$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 , */
Shorter alternative as Felix Kling pointed out:
$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);
Either this should work:
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);
?>
Here is how I would probably do it.
$str = "KEYWORD1,KEYWORD2,KEYWORD3";
$keywords = explode(',', $str);
$links = array();
foreach($keywords as $keyword) {
$links[] = "<a href='home'>$keyword</a>";
}
echo implode(', ', $links);
精彩评论