diff --git a/docs/usage.md b/docs/usage.md index c1a9d99..6fdfc13 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -72,5 +72,5 @@ You can start creating your regex by using `Regex::build()`. The `build()` metho - IPv6 address - mac address - [`email`](usage/patterns#email) -- url +- [`url`](usage/patterns#url) - [`credit card`](usage/patterns#credit-card) diff --git a/docs/usage/patterns.md b/docs/usage/patterns.md index 543536e..a63d0b4 100644 --- a/docs/usage/patterns.md +++ b/docs/usage/patterns.md @@ -49,6 +49,21 @@ $pattern = Regex::build([\Rudashi\Patterns\EmailPattern::class]) // /^\w+(?:[\.\-]\w+)*@([\w-]+\.)+[\w-]{2,}$/ ``` +### `Url` + +To check whether a given text contains a website, you can use the predefined `UrlPattern` pattern. It only accepts addresses with the **http** or https **protocol** entered. + +```php +use Rudashi\Regex; + +$pattern = Regex::build([\Rudashi\Patterns\UrlPattern::class]) + ->start() + ->url() + ->end(); + +// /^https?\:\/\/[^-][a-z\d.-]+[^-]\.[a-z]{2,}(\/[a-z\d\/-]*)?$/ +``` + ### `Credit card` To find if there is any credit card number in a given text, you can use the predefined `CreditCardPattern` pattern. The pattern identifies **Visa** and **MasterCard** cards. diff --git a/src/Patterns/UrlPattern.php b/src/Patterns/UrlPattern.php new file mode 100644 index 0000000..565795e --- /dev/null +++ b/src/Patterns/UrlPattern.php @@ -0,0 +1,15 @@ +start() + ->exactly('https')->zeroOrOne() + ->then("://") + ->not->character('-') + ->anyOf( + fn (FluentBuilder $fluent) => $fluent->lowerLetter()->digit()->character('.-') + )->oneOrMore() + ->not->character('-') + ->then('.') + ->lowerLetter()->min(2) + ->maybe(fn (FluentBuilder $fluent) => $fluent->exactly('/')->anyOf( + fn (FluentBuilder $fluent) => $fluent->lowerLetter()->digit()->exactly('/')->character('-') + )->zeroOrMore()) + ->utf8() + ->end(); + + expect($regex) + ->toBeInstanceOf(FluentBuilder::class) + ->get()->toBe('/^https?\:\/\/[^-][a-z\d.-]+[^-]\.[a-z]{2,}(\/[a-z\d\/-]*)?$/u') + ->check()->toBe($expectation); +})->with('urls'); + +describe('predefined URL pattern', function () { + beforeEach(function () { + $this->builder = new FluentBuilder(patterns: [UrlPattern::class]); + }); + + it('validates', function (string $context, bool $expectation) { + $regex = $this->builder->setContext($context)->start()->url()->end(); + + expect($regex->check()) + ->toBe($expectation); + })->with('urls'); + + it('finds a credit cards in text', function () { + $context = "Find the best business solutions at http://develop-yourself.com. Need some inspiration? Visit \n + www.creative-business.com. And if you're looking for entertainment, check out https://creative-hobbies.com!"; + + $regex = $this->builder->setContext($context)->url(); + + expect($regex->match()) + ->toHaveCount(2) + ->toMatchArray([ + 'http://develop-yourself.com', + 'https://creative-hobbies.com', + ]); + }); +});