4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Finder;
15 * Glob matches globbing patterns against text.
17 * if match_glob("foo.*", "foo.bar") echo "matched\n";
19 * // prints foo.bar and foo.baz
20 * $regex = glob_to_regex("foo.*");
21 * for (array('foo.bar', 'foo.baz', 'foo', 'bar') as $t)
23 * if (/$regex/) echo "matched: $car\n";
26 * Glob implements glob(3) style matching that can be used to match
27 * against text, rather than fetching names from a filesystem.
29 * Based on the Perl Text::Glob module.
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>
39 * Returns a regexp which is the equivalent of the glob pattern.
41 * @param string $glob The glob pattern
42 * @param bool $strictLeadingDot
43 * @param bool $strictWildcardSlash
44 * @param string $delimiter Optional delimiter
46 * @return string regex The regexp
48 public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true, $delimiter = '#')
54 $sizeGlob = \strlen($glob);
55 for ($i = 0; $i < $sizeGlob; ++$i) {
57 if ($firstByte && $strictLeadingDot && '.' !== $car) {
58 $regex .= '(?=[^\.])';
61 $firstByte = '/' === $car;
63 if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) {
65 if (!isset($glob[$i + 3])) {
69 if ($strictLeadingDot) {
70 $car = '(?=[^\.])'.$car;
73 $car = '/(?:'.$car.')*';
74 $i += 2 + isset($glob[$i + 3]);
76 if ('/' === $delimiter) {
77 $car = str_replace('/', '\\/', $car);
81 if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
83 } elseif ('*' === $car) {
84 $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
85 } elseif ('?' === $car) {
86 $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
87 } elseif ('{' === $car) {
88 $regex .= $escaping ? '\\{' : '(';
92 } elseif ('}' === $car && $inCurlies) {
93 $regex .= $escaping ? '}' : ')';
97 } elseif (',' === $car && $inCurlies) {
98 $regex .= $escaping ? ',' : '|';
99 } elseif ('\\' === $car) {
114 return $delimiter.'^'.$regex.'$'.$delimiter;