Convert comma separated string into array

前端 未结 10 1533
南笙
南笙 2020-12-17 20:08

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         


        
相关标签:
10条回答
  • 2020-12-17 20:29

    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);
    
    0 讨论(0)
  • 2020-12-17 20:29
    function info_get_tags($arg)
    {
        global $u;
        if (empty($arg)) return '';
        return ltrim(preg_replace('/([^\,]+)/', ' <a href="' . $u . '/${1}/" title="${1}">${1}</a>', $arg));
    }
    
    0 讨论(0)
  • 2020-12-17 20:35
    $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>
    
    0 讨论(0)
  • 2020-12-17 20:36

    Try this short code

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

    $string = explode(',', $string);
       foreach( $string as $link){
       echo '<a href="tag/'.$link.'">'.$link.'</a>';
    }

    0 讨论(0)
  • 2020-12-17 20:37

    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);
    
    }
    
    0 讨论(0)
  • 2020-12-17 20:38

    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);
    } 
    
    0 讨论(0)
提交回复
热议问题