Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

php - Convert comma separated string into array

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...