PHP code to split a string into a list of tags
February 13th, 2006
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
)
/*
?>
Entry Filed under: PHP
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed