1: <?php
2:
3: /*
4: * This file is part of the Symfony package.
5: *
6: * (c) Fabien Potencier <fabien@symfony.com>
7: *
8: * For the full copyright and license information, please view the LICENSE
9: * file that was distributed with this source code.
10: */
11:
12: namespace Symfony\Component\Finder;
13:
14: /**
15: * Glob matches globbing patterns against text.
16: *
17: * if match_glob("foo.*", "foo.bar") echo "matched\n";
18: *
19: * // prints foo.bar and foo.baz
20: * $regex = glob_to_regex("foo.*");
21: * for (array('foo.bar', 'foo.baz', 'foo', 'bar') as $t)
22: * {
23: * if (/$regex/) echo "matched: $car\n";
24: * }
25: *
26: * Glob implements glob(3) style matching that can be used to match
27: * against text, rather than fetching names from a filesystem.
28: *
29: * Based on the Perl Text::Glob module.
30: *
31: * @author Fabien Potencier <fabien@symfony.com> PHP port
32: * @author Richard Clamp <richardc@unixbeard.net> Perl version
33: * @copyright 2004-2005 Fabien Potencier <fabien@symfony.com>
34: * @copyright 2002 Richard Clamp <richardc@unixbeard.net>
35: */
36: class Glob
37: {
38: /**
39: * Returns a regexp which is the equivalent of the glob pattern.
40: *
41: * @param string $glob The glob pattern
42: * @param Boolean $strictLeadingDot
43: * @param Boolean $strictWildcardSlash
44: *
45: * @return string regex The regexp
46: */
47: public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true)
48: {
49: $firstByte = true;
50: $escaping = false;
51: $inCurlies = 0;
52: $regex = '';
53: $sizeGlob = strlen($glob);
54: for ($i = 0; $i < $sizeGlob; $i++) {
55: $car = $glob[$i];
56: if ($firstByte) {
57: if ($strictLeadingDot && '.' !== $car) {
58: $regex .= '(?=[^\.])';
59: }
60:
61: $firstByte = false;
62: }
63:
64: if ('/' === $car) {
65: $firstByte = true;
66: }
67:
68: if ('.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
69: $regex .= "\\$car";
70: } elseif ('*' === $car) {
71: $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
72: } elseif ('?' === $car) {
73: $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
74: } elseif ('{' === $car) {
75: $regex .= $escaping ? '\\{' : '(';
76: if (!$escaping) {
77: ++$inCurlies;
78: }
79: } elseif ('}' === $car && $inCurlies) {
80: $regex .= $escaping ? '}' : ')';
81: if (!$escaping) {
82: --$inCurlies;
83: }
84: } elseif (',' === $car && $inCurlies) {
85: $regex .= $escaping ? ',' : '|';
86: } elseif ('\\' === $car) {
87: if ($escaping) {
88: $regex .= '\\\\';
89: $escaping = false;
90: } else {
91: $escaping = true;
92: }
93:
94: continue;
95: } else {
96: $regex .= $car;
97: }
98: $escaping = false;
99: }
100:
101: return '#^'.$regex.'$#';
102: }
103: }
104: