diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bdbaf3..7f78b7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 2.4.1 under development +- New #137: Add `StringHelper::matchAnyRegex()` method as a facade for `CombinedRegexp` (@vjik) - Enh #128: Add more specific psalm type for result of `StringHelper::base64UrlEncode()` method (@vjik) ## 2.4.0 December 22, 2023 diff --git a/README.md b/README.md index aafb961..df04325 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,7 @@ Overall the helper has the following method groups. ### Other +- matchAnyRegex - parsePath - split diff --git a/src/StringHelper.php b/src/StringHelper.php index f395156..0bf4497 100644 --- a/src/StringHelper.php +++ b/src/StringHelper.php @@ -729,6 +729,27 @@ public static function findBetweenLast(string $string, string $start, ?string $e return mb_substr($string, $startPos, $endPos - $startPos); } + /** + * Checks if a given string matches any of the provided patterns. + * + * Note that patterns should be provided without delimiters on both sides. For example, `te(s|x)t`. + * + * @see https://www.php.net/manual/reference.pcre.pattern.syntax.php + * @see https://www.php.net/manual/reference.pcre.pattern.modifiers.php + * + * @param string $string The string to match against the patterns. + * @param string[] $patterns Regular expressions without delimiters on both sides. + * @param string $flags Flags to apply to all regular expressions. + */ + public static function matchAnyRegex(string $string, array $patterns, string $flags = ''): bool + { + if (empty($patterns)) { + return false; + } + + return (new CombinedRegexp($patterns, $flags))->matches($string); + } + /** * Ensure the input string is a valid UTF-8 string. * diff --git a/tests/StringHelper/MatchAnyRegexTest.php b/tests/StringHelper/MatchAnyRegexTest.php new file mode 100644 index 0000000..a7df6a3 --- /dev/null +++ b/tests/StringHelper/MatchAnyRegexTest.php @@ -0,0 +1,46 @@ +assertSame($expected, $result); + } + + /** + * @testWith [true, "test"] + * [false, "hello"] + */ + public function testWithoutFlags(bool $expected, string $string): void + { + $result = StringHelper::matchAnyRegex($string, ['te[sx]t', 'm(o|a)n']); + $this->assertSame($expected, $result); + } + + public function testWithoutPatterns(): void + { + $result = StringHelper::matchAnyRegex('test', []); + $this->assertFalse($result); + } +}