Convert comma separated string into array

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

    Another solution:

    $html = trim(preg_replace('/([^,]+)/', ' \1', $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 ' ' . htmlspecialchars($tag) . '';
    }, $string));
    

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

    More regex is always good!

提交回复
热议问题