3 namespace Drupal\Component\Utility;
6 * Defines a class that can explode and implode tags.
13 * Explodes a string of tags into an array.
16 * A string to explode.
21 public static function explode($tags) {
22 // This regexp allows the following types of user input:
23 // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
24 $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
25 preg_match_all($regexp, $tags, $matches);
26 $typed_tags = array_unique($matches[1]);
29 foreach ($typed_tags as $tag) {
30 // If a user has escaped a term (to demonstrate that it is a group,
31 // or includes a comma or quote character), we remove the escape
32 // formatting so to save the term into the database as the user intends.
33 $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
43 * Encodes a tag string, taking care of special cases like commas and quotes.
51 public static function encode($tag) {
52 if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
53 return '"' . str_replace('"', '""', $tag) . '"';
59 * Implodes an array of tags into a string.
65 * The imploded string.
67 public static function implode($tags) {
69 foreach ($tags as $tag) {
70 $encoded_tags[] = self::encode($tag);
72 return implode(', ', $encoded_tags);