将逗号分隔的字符串转换为数组

将逗号分隔的字符串转换为数组

本文介绍了将逗号分隔的字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用逗号分隔的字符串,该字符串包含标签列表,并希望将其转换为数组以获取每个标签的链接.

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.

示例:

$string = 'html,css,php,mysql,javascript';

我想要这样:

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

我有此功能,其中$ arg ='html,css,php,mysql,javascript':

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.

推荐答案

就像您explode d一样,您可以 implode 再次:

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

这篇关于将逗号分隔的字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:56