0

I have tags that separated by ; in MySQL database and they are all in one field.

so whenever I try to load the field. the data will be displayed like this :

tag1 ; tag2 ; tag3

What I want to do, is to add url to every tag. basically I want to display it like this:

<a href="http://example.com/tag1">tag1</a> 
<a href="http://example.com/tag2">tag2</a>  
<a href="http://example.com/tag3">tag3</a>

I was thinking to use str_replace to replace the ; with </a> but how do I do the beginning of each tag!

Is there a code that does that better than str_replace?

4

3 に答える 3

8

You may "cheat" and just explode on ; and loop through the resulting array.


This is almost never the right approach though! You should always strive to normalize your database (and if you don't you should know exactly why you choose not to). As it currently stands your table is not even adhering to the first normal form, which states that you should have only atomic data in each field. The reason this is a bad idea is because you will have a hard time querying the table (for example getting all rows with a certain tag).

What you should do is create a separate table for the tags, containing two fields: postid (from the table you already have) and tag. Then use a JOIN operation to join them together.

于 2012-08-18T21:10:50.570 に答える
4
$tags = "tag1 ; tag2 ; tag3";
$t = explode(";",$tags);
$string = '';
foreach($t as $value) {
   $value = trim($value);
   $string .= "<a href='http://example.com/$value'>$value</a>";
}
于 2012-08-18T21:13:49.533 に答える
1
$string = "tag1 ; tag2 ; tag3";
$tags = explode(" ; ", $string);
foreach ($tags as $tag) {
  echo '<a href="http://example.com/'. $tag .'">' . $tag .'</a>';
}
于 2012-08-18T21:11:10.423 に答える