4

Is there a way to split a comma separated string at the commas, without first exploding it and looping through the array? I've got a string that is output from a database, which comes out the way I've shown below. I then split them into links.

But, given the string the way it is, can I get it into 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 />';
}

?>

The final out of the above is:

<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 />
2
  • The only other ways I can htink of would be use an array - which would still require looping - or regex - which would also require looping. You've got to loop because each tag has to be extrapolated and given its own link. Sep 14, 2014 at 14:13
  • 3
    What is the issue with doing it this way?
    – Sean
    Sep 14, 2014 at 14:13

4 Answers 4

6

You can use a single regex:

preg_replace('~\s?([^\s,]+)\s?(?:,|$)~', '<a href="$1">$1</a><br />' . PHP_EOL, $tags);
  • \s? matches a single whitespace or nothing
  • ([^\s,]+) matches everything until it reaches a whitespace or a comma and captures it
  • \s? again, matches a single whitespace or nothing
  • (?:,|$) matches either a comma or end of string
2

You could use array_walk instead of foreach but it amounts to pretty much the same.

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

If you want to use tested, robust code that won't bug out when you have some values surrounded with quotes to escape an actual comma within the quoted string (where the naive approaches would still split), you could try using the str_getcsv function.

1
<?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>';

?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.