Create links with tags registered in the database

Asked

Viewed 216 times

0

I have a field in the MySQL with the following content:

Alesso; Anitta; Billboard; Marshmello; Poo Bear

I need to take each of the values separately and create a link like this:

<a href="#">Alesso</a>

I can’t read each value individually.

4 answers

2


You need to break the string in a array, use the exploded method of PHP: Explodes:

$arr = 'Alesso; Anitta; Billboard; Marshmello; Poo Bear';
$EXP = explode(';', $arr);
foreach($EXP as $link)
{
      echo '<a href="#">'.$link.'</a>'.'<br>';
}
  • If the pattern is "; ", should not in the explode() contain the space after the semicolon? In HTML a space is returning, although HTML ignores this space.

  • I think it doesn’t make a difference overall, unless you want to break with 100% accuracy

  • in that case it is best to do just by ; and use the function trim in the variable $link

1

If this field will always be in this pattern, you can do it in mysql with CONCAT and REPLACE, e.g.:

SELECT
    -- Aqui você substitui o x.nomes pela sua tabela.campo
    CONCAT('<a href="#">' , REPLACE(x.nomes, '; ', '</a><a href="#">') , '</a>') AS links
FROM
    -- Aqui você substitui pela sua tabela
    (SELECT 'Alesso; Anitta; Billboard; Marshmello; Poo Bear' AS nomes) AS x;

1

example - ideone

$str = 'Alesso; Anitta; Billboard; Marshmello; Poo Bear';
//para evitar de retirar espaços em nomes compostos
$output  = str_replace("; ", ";", $str);
$result = explode(';', $output);
foreach($result as $link)
{
  echo "<a href='#'>".$link."</a>\n";
}
  • str_replace - replaces all occurrences of the search string with the replace string
  • explode - splits a main string into smaller parts based on a splitter character

0

The best way is using a repetition system

$sql = "select coluna from tabela";

$result = mysqli_query($conexao, $sql);

while($dados = mysqli_fecth_array($result)) {
 echo "<a href=".base64_encode($dados['coluna']).".php>".$dados['coluna']."</a>";
}

Remember that an encrypted link was created in Base64. The advantage is when there are spaces " ", this character not accepted as url by apache, are encrypted.

To decrypt use

base64_decode($string);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.