Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated string into array

Tags:

arrays

string

php

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 = 'html,css,php,mysql,javascript';

I want to make it like this:

<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>

So the result will be a string containing comma separated links with a space after each link and with no comma after the last link.

I have this function where $arg = 'html,css,php,mysql,javascript':

function info_get_tags( $arg ) {
    global $u;

    $tagss = '';
    if ( $arg == '' ) {
        return '';
    } else {
        $tags_arr = explode( ',' , $arg );
        foreach ( $tags_arr as $tag ) {
            $tags = '<a href="' . $u . 'tag/' . $tag . '/" title="' . $tag . '">' . $tag . '</a>';
            $tagss .= $tags;
        }

        return $tagss;
    }
}

This script works for me but without commas and spaces and if we add a comma and a space here:

$tags = '<a href="' . $u . 'tag/' . $tag . '/">' . $tag . '</a>, ';

we get commas and spaces but there will be a trailing comma after the last link.

like image 503
med Avatar asked Apr 30 '11 22:04

med


2 Answers

Just like you exploded you can implode again:

$tags = explode(',', $arg);
foreach ($tags as &$tag) {
    $tag = '<a href="' . $u . 'tag/' . $tag . '/" title="' . $tag . '">' . $tag . '</a>';
}

return implode(', ', $tags);
like image 50
NikiC Avatar answered Oct 06 '22 19:10

NikiC


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);
} 
like image 21
Nick Avatar answered Oct 06 '22 18:10

Nick