逐个显示标签


display tags one by one

嗨,我有标签在我的数据库中的一行称为标签。以逗号分隔。

例如,它们在数据库中存储为tag1,tag2,tag3

我想从数据库中检索它们,并分别一个接一个地显示它们,在显示每个标记之前,我想将其链接到URL。

这是我目前为止所做的,

$keywords = strip_tags($blog_query_results['keywords']); //Retrives the tags from the database
echo wordwrap(stripslashes($keywords), 65, "<br>",true); // this prints tag1,tag2, and so on.

在打印它们时,我想将tag1, tag2和tag3链接到不同的url。

如果你有一个像这样的字符串:

$tags = 'tag1,tag2,tag3';

您可以使用 explode() 函数来获取标签数组:

$arr = explode(',', $tags);

然后,只需遍历该数组,为每个项目建立链接-通常使用foreach():

foreach ($arr as $t) {
    echo '<a href="...">' . htmlspecialchars($t, ENT_COMPAT, 'UTF-8') . '</a><br />';
}


作为旁注:如果您在单个字段中存储多个信息,那么您的数据库设计可能有点错误。

如果一篇文章有3个标签,你应该有3行(每个标签一个),要么:

  • tags表中
  • 或者在poststags表之间的连接表中。

你可以这样做:

$tags = explode(',', $keywords);
foreach($tags as $tag)
{
    echo "<a href='...' >$tag</a>";
}

等等…