Tags.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Defines a class that can explode and implode tags.
  5. *
  6. * @ingroup utility
  7. */
  8. class Tags {
  9. /**
  10. * Explodes a string of tags into an array.
  11. *
  12. * @param string $tags
  13. * A string to explode.
  14. *
  15. * @return array
  16. * An array of tags.
  17. */
  18. public static function explode($tags) {
  19. // This regexp allows the following types of user input:
  20. // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
  21. $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
  22. preg_match_all($regexp, $tags, $matches);
  23. $typed_tags = array_unique($matches[1]);
  24. $tags = [];
  25. foreach ($typed_tags as $tag) {
  26. // If a user has escaped a term (to demonstrate that it is a group,
  27. // or includes a comma or quote character), we remove the escape
  28. // formatting so to save the term into the database as the user intends.
  29. $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
  30. if ($tag != "") {
  31. $tags[] = $tag;
  32. }
  33. }
  34. return $tags;
  35. }
  36. /**
  37. * Encodes a tag string, taking care of special cases like commas and quotes.
  38. *
  39. * @param string $tag
  40. * A tag string.
  41. *
  42. * @return string
  43. * The encoded string.
  44. */
  45. public static function encode($tag) {
  46. if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
  47. return '"' . str_replace('"', '""', $tag) . '"';
  48. }
  49. return $tag;
  50. }
  51. /**
  52. * Implodes an array of tags into a string.
  53. *
  54. * @param array $tags
  55. * An array of tags.
  56. *
  57. * @return string
  58. * The imploded string.
  59. */
  60. public static function implode($tags) {
  61. $encoded_tags = [];
  62. foreach ($tags as $tag) {
  63. $encoded_tags[] = self::encode($tag);
  64. }
  65. return implode(', ', $encoded_tags);
  66. }
  67. }