PHP gets values ​​from comma, comma separated, no breaks or loops

Is there a way to split a comma separated string into a comma without blowing it up first and looping through the array? I have a row that is output from a database that appears as I showed below. Then I divided them into links.

But, given the string as it is, can I get it in the links without doing it the way I do below?

<?php

$tags = "fiction,non-fiction,horror,romance"; 

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

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

?>

Last of the above:

<a href="fiction">fiction</a><br />
<a href="non-fiction">non-fiction</a><br />
<a href="horror">horror</a><br />
<a href="romance">romance</a><br />
+4
source share
4 answers

You can use one regex:

preg_replace('~\s?([^\s,]+)\s?(?:,|$)~', '<a href="$1">$1</a><br />' . PHP_EOL, $tags);
  • \s? matches one space or nothing
  • ([^\s,]+) matches all until it reaches a space or a comma and fixes it
  • \s? ,
  • (?:,|$)
+6

array_walk foreach, .

 array_walk(explode(',',$tags),function($tag){
     echo '<a href="'.$tag.'">'.$tag.'</a><br />';
    });
+2

, , , , , ( ), str_getcsv.

+2
<?php
$tags = "fiction,non-fiction,horror,romance"; 
 /*You can achieve that by using regular expresions*/
$pattern = '~(?|select ([a-z][^\W_]*+) | *+([a-z][^\W,_]*+) *+,?)~i';
   //str_replace() function used for breaking the newline.
 echo '<a href="'.$tags.'">'.str_replace(',', "<br/>", $tags).'</a>';

?>
+1

All Articles