StringUtil.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Sabre\VObject;
  3. /**
  4. * Useful utilities for working with various strings.
  5. *
  6. * @copyright Copyright (C) fruux GmbH (https://fruux.com/)
  7. * @author Evert Pot (http://evertpot.com/)
  8. * @license http://sabre.io/license/ Modified BSD License
  9. */
  10. class StringUtil
  11. {
  12. /**
  13. * Returns true or false depending on if a string is valid UTF-8.
  14. *
  15. * @param string $str
  16. *
  17. * @return bool
  18. */
  19. public static function isUTF8($str)
  20. {
  21. // Control characters
  22. if (preg_match('%[\x00-\x08\x0B-\x0C\x0E\x0F]%', $str)) {
  23. return false;
  24. }
  25. return (bool) preg_match('%%u', $str);
  26. }
  27. /**
  28. * This method tries its best to convert the input string to UTF-8.
  29. *
  30. * Currently only ISO-5991-1 input and UTF-8 input is supported, but this
  31. * may be expanded upon if we receive other examples.
  32. *
  33. * @param string $str
  34. *
  35. * @return string
  36. */
  37. public static function convertToUTF8($str)
  38. {
  39. if (!mb_check_encoding($str, 'UTF-8') && mb_check_encoding($str, 'ISO-8859-1')) {
  40. $str = mb_convert_encoding($str, 'UTF-8', 'ISO-8859-1');
  41. }
  42. // Removing any control characters
  43. return preg_replace('%(?:[\x00-\x08\x0B-\x0C\x0E-\x1F\x7F])%', '', $str);
  44. }
  45. }