Utils.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of phpDocumentor.
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. *
  9. * @link http://phpdoc.org
  10. */
  11. namespace phpDocumentor\Reflection;
  12. use phpDocumentor\Reflection\Exception\PcreException;
  13. use function preg_last_error;
  14. use function preg_split as php_preg_split;
  15. abstract class Utils
  16. {
  17. /**
  18. * Wrapper function for phps preg_split
  19. *
  20. * This function is inspired by {@link https://github.com/thecodingmachine/safe/blob/master/generated/pcre.php}. But
  21. * since this library is all about performance we decided to strip everything we don't need. Reducing the amount
  22. * of files that have to be loaded, ect.
  23. *
  24. * @param string $pattern The pattern to search for, as a string.
  25. * @param string $subject The input string.
  26. * @param int|null $limit If specified, then only substrings up to limit are returned with the
  27. * rest of the string being placed in the last substring. A limit of -1 or 0 means "no limit".
  28. * @param int $flags flags can be any combination of the following flags (combined with the | bitwise operator):
  29. * *PREG_SPLIT_NO_EMPTY*
  30. * If this flag is set, only non-empty pieces will be returned by preg_split().
  31. * *PREG_SPLIT_DELIM_CAPTURE*
  32. * If this flag is set, parenthesized expression in the delimiter pattern will be captured
  33. * and returned as well.
  34. * *PREG_SPLIT_OFFSET_CAPTURE*
  35. * If this flag is set, for every occurring match the appendant string offset will also be returned.
  36. * Note that this changes the return value in an array where every element is an array consisting of the
  37. * matched string at offset 0 and its string offset into subject at offset 1.
  38. *
  39. * @return string[] Returns an array containing substrings of subject split along boundaries matched by pattern
  40. *
  41. * @throws PcreException
  42. */
  43. public static function pregSplit(string $pattern, string $subject, ?int $limit = -1, int $flags = 0) : array
  44. {
  45. $parts = php_preg_split($pattern, $subject, $limit, $flags);
  46. if ($parts === false) {
  47. throw PcreException::createFromPhpError(preg_last_error());
  48. }
  49. return $parts;
  50. }
  51. }