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 />
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 stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With