How to use Str::is() is Laravel for string comparison and pattern matching
While using Laravel, the Str class offers a number of handy string manipulation functions. One of the less popular yet powerful functions is Str::is(). This function allows you to verify whether a given string fits a particular pattern — very handy when dealing with wildcards.
So in this blog we will learn how to use Str::is() in Laravel, its use cases with several examples.
In this blog, we’ll see:
- ✅ What is Str::is()?
- 🔧 How it works internally
- 💡 Examples and common patterns
- 🚨 When and why to use it
✅ What is Str::is()?
Str::is() is a static function offered by Laravel's Illuminate\Support\Str class. It lets you check whether a string matches a specified pattern, possibly including the * wildcard. In real world for pattern matching we normally use preg_match(). With Str::is() we can avoid using preg_match() for simple pattern matching to keep our code simple and easy to understand.
Syntax :
Str::is(string $pattern, string $value): bool
It returns true if pattern matches otherwise it returns false.
🔧 How it works internally :
when use this Str::is() syntax, behind this syntax, it converts this to regex for pattern matching.
Str::is('thedev*', 'thedevnerd'); // true
refers to -
preg_match('/^thedev.*$/', 'thedevnerd');
💡 Examples and common patterns :
Simple Matching :
use Illuminate\Support\Str; Str::is('hello', 'hello'); // true Str::is('hello', 'world'); // false
Wildcard Match :
Str::is('foo*', 'foobar'); // true Str::is('foo*', 'fooBarBaz'); // true Str::is('foo*', 'barfoo'); // false
Wildcard In the Middle :
Str::is('user/*/profile', 'user/123/profile'); // true Str::is('user/*/profile', 'user/abc/profile'); // true Str::is('user/*/profile', 'user/abc/dashboard'); // false
Match against multiple patterns :
Str::is(['admin/*', 'user/*'], 'user/dashboard'); // true Str::is(['admin/*', 'api/*'], 'web/home'); // false
🚨 When to Use Str::is() :
- You require pattern-based string matching with wildcards.
- You prefer a more readable alternative to preg_match() or strpos().
- You're working with dynamic URLs, file paths, or permission verification.
Avoid Str::is() for complex regex matching — it’s intentionally kept simple with just * as a wildcard. If you need regex, use preg_match() instead.