I have a MySQL field called "tags" an example result. The single field has a list of text with comma separated values.
A real example:
red, pants, shoes, heels, lookbook
I want to somehow use find and replace or implode feature to print out this row as separate links.
My guess so far:
<?php
$tag=$row["tags"];
whilst (!$tag=="") {
echo '<a href="/tags/$tag">$tag</a>, "';
}
?>
explode()
foreach
implode()
example:
$tags = explode(", ", $row["tags"]);
foreach ($tags as &$tag) {
$tag = "<a href=\"/tags/$tag\">$tag</a>";
}
echo implode(", ", $tags);
Another approach would be using preg_replace
:
$row['tags'] = "banana, apple, peach, strawberry";
echo preg_replace( '#([^,\s]+)#is',
'<a href="/tags/$1">$1</a>',
$row['tags']);
You should probably take a look at this answer first SQL Array Search (how to store such an information in the database). If you still want to use coma separated list, the best way is probably using explode()
, array_map()
and implode()
:
function generateLink( $tag){
$tag = htmlspecialchars( trim( $tag));
$str = "<a href=\"/tags/$tag\">$tag</a>";
}
$tags = explode( ',', $row['tags']);
$new_tags = array_map( 'generateLink', $tags);
echo implode( ', ', $new_tags);
// Of course you can chain it to:
echo implode( ', ', array_map( 'generateLink', explode( ',', $row['tags'])));
However if you use correct database design you should this SELECT
(displaying one product):
SELECT tags.name
FROM tags_products
INNER JOIN tags ON tags_products.tag_id = tags.id
WHERE tags_products,product_id = ?
And with php:
$q = $db->query( 'mentioned select');
$result = array();
while( $row = $q->fetch_assoc()){
$result[] = genereateLink( $row['name']);
}
And in case of mass listing of product to increase performance use this select with GROUP_CONCAT
:
SELECT products.id, products.name, GROUP_CONCAT(tags.name ASC SEPARATOR ', ') AS tags
FROM products
LEFT JOIN tags_products ON tags_producsts.product_id = products.id
INNER JOIN tags ON tags_products.tag_id = tags.id
GROUP BY products.id
And apply the first mentioned code on $row['tags']
:)