Skip to content

Instantly share code, notes, and snippets.

@Patabugen
Created August 2, 2022 17:18
Show Gist options
  • Save Patabugen/951d6bf96585bd4ca8a2e63909ba2d86 to your computer and use it in GitHub Desktop.
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
<?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