Convert comma separated string into array

前端 未结 10 1540
南笙
南笙 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:42

    Try this

    $tagss = trim($tagss);    
    return substr($tagss, 0 , strlen($tagss)-1);
    
    0 讨论(0)
  • 2020-12-17 20:46

    The workaround(!) would be to remove the unwanted trailing characters afterwards:

    $tagss = rtrim($tagss, ", ");
    

    This rtrim removes any mix of spaces and commas from the right end of the string.

    Btw, you could use str_getcsv instead of explode, which also handles input spaces better.

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

    Another solution:

    $html = trim(preg_replace('/([^,]+)/', ' <a href="/tags/\1" title="\1">\1</a>', $string));
    

    Or if you have to html encode the tags (always smart, since you're creating html from text):

    $html = trim(preg_replace_callback('/([^,]+)/', function($match) {
        $tag = $match[1];
        return ' <a href="/tags/' . urlencode($tag) . '" title="' . htmlspecialchars($tag) . '">' . htmlspecialchars($tag) . '</a>';
    }, $string));
    

    So this $string would work too: "tag with space,html,css,php,mysql,javascript"

    More regex is always good!

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

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