Archive for February 13th, 2006

PHP code to split a string into a list of tags

I wrote this code for a project I have been working on and figured it might be useful for others. The function splits a string into tags (i.e. the sort that can be attached to blog posts or social bookmarks etc.)

Tags are written as a comma seperated list, can have multiple words and contain commas if encapsulated by double quotes. Hope someone finds it useful!

< ?php
    function explodeTagString ($subject)
    {
        // split the string, populates the $tags array
        preg_match_all('/[^,]*\".*\"|[^,]\s*[^,]+\s*[^,]/',
            $subject, $tags);
	
        // loop through $tags and trims spaces and double
        // quote (\") chars this is a bit of a hack (I am
        // sure it could be built into the regex above).
        foreach ($tags[0] as $k=>$t) {
            $tags[$k] = trim($t, ‘” ‘);
        }
	
        return $tags;
    }
	
    // A little test case
    $test_tag_string = ‘test tag, “x, y and z”, foo, bar’;
    $tags = explodeTagString($test_tag_string);
    print_r($tags);
    /*
        Should output:
        Array
        (
            [0] => test tag
            [1] => x, y and z
            [2] => foo
            [3] => bar
        )
    /*
?>

Add comment February 13th, 2006


Calendar

February 2006
M T W T F S S
« Jan    
 12345
6789101112
13141516171819
20212223242526
2728  

Posts by Month

Posts by Category

Support Firefox

Ads