I have a comma separated string, which consists of a list of tags and want to convert it to array to get a link for every tag.
Example:
$string = \'h
Why not put all tags in an array when you are creating them, and later explode the array and add the commas and spaces between the tags.
foreach ( $tags_arr as $tag ) {
$tags = '<a href="' . $u . 'tag/' . $tag . '/" title="' . $tag . '">' . $tag . '</a>';
$tagss[] = $tags;
}
$tagss = explode(', ', $tagss);
function info_get_tags($arg)
{
global $u;
if (empty($arg)) return '';
return ltrim(preg_replace('/([^\,]+)/', ' <a href="' . $u . '/${1}/" title="${1}">${1}</a>', $arg));
}
$string = 'html,css,php,mysql,javascript';
puts $string.split(/,/).map { |tag| "<a href=\"tag/#{tag}\">#{tag}</a>"}.join(", ")
result:
<a href="tag/html">html</a>, <a href="tag/css">css</a>, <a href="tag/php">php</a>, <a href="tag/mysql">mysql</a>, <a href="tag/javascript">javascript</a>
Try this short code
$string = 'html,css,php,mysql,javascript';
$string = explode(',', $string);
foreach( $string as $link){
echo'<a href="tag/'.$link.'">'.$link.'</a>';
}
Easiest way is to the html into an array (each tag link is an array element) and then implode on ,
...
if ( $arg == '' ) {
return '';
} else {
$tags_arr = explode( ',' , $arg );
$tags = array();
$tagtpl = '<a href="%s" title="%s">%s</a>';
foreach ( $tags_arr as $tag ) {
$url = $u . 'tag/' . $tag . '/';
$tags[] = sprintf($tagtpl, $url, $tag, $tag);
}
return implode(', ', $tags);
}
Here's an alternative that uses array_map instead of the foreach loop:
global $u;
function add_html($tag){
return('<a href="' . $u . 'tag/' . $tag . '/" title="' . $tag . '">' . $tag . '</a>');
}
function get_tags($taglist){
$tags_arr = array_map("add_html", explode( ',' , $taglist));
return implode(", " , $tags_arr);
}