Created
August 2, 2022 17:18
-
-
Save Patabugen/951d6bf96585bd4ca8a2e63909ba2d86 to your computer and use it in GitHub Desktop.
isMatch macro for Laravel fluent strings to check if a string matches a regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
use Illuminate\Support\ServiceProvider; | |
use Illuminate\Support\Str; | |
use Illuminate\Support\Stringable; | |
/** | |
* Add isMatch() method to Str helper and Stringable objects. isMatch is the love hild | |
* of is() and match() - which tells you if the string matches the given regex. | |
* | |
* Str::of('Abc123')->isMatch('/[A-z]{3}[1-9]{3}/'); // true | |
* Str::of('Abc123')->isMatch('/[A-z]{3}[1-9]{2}/'); // true | |
* Str::of('Abc123')->isMatch('/[A-z]{3}[1-9]{2}^/'); // false (because of the end of string anchor) | |
*/ | |
class StrServiceProvider extends ServiceProvider | |
{ | |
public function boot() | |
{ | |
Str::macro('isMatch', function ($pattern, $value) { | |
return preg_match($pattern, $value) === 1; | |
}); | |
Stringable::macro('isMatch', function ($pattern) { | |
return Str::matches($pattern, $this->value); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment