Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get values from a comma separated string at commas without exploding and looping [duplicate]

Tags:

arrays

string

php

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 />
like image 752
jmenezes Avatar asked Dec 20 '22 11:12

jmenezes


1 Answers

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
like image 150
Jonan Avatar answered Dec 22 '22 01:12

Jonan