Laravel Tutorials

Enable Flexible Pattern Matching with Laravel's Case-Insensitive Str::is Method

Published
Enable Flexible Pattern Matching with Laravel's Case-Insensitive Str::is Method image

Laravel enhances string pattern matching by adding case-insensitive support to the Str::is method, providing more flexible and user-friendly string comparisons with wildcard patterns.

The enhanced Str::is method accepts a third parameter for case-insensitive matching:

use Illuminate\Support\Str;
 
// Simple string matching
Str::is('Admin', 'admin', true); // true
 
// Wildcard pattern matching
Str::is('*.jpg', 'photo.JPG', true); // true
 
// Prefix matching
Str::is('SKU123*', 'sku12345', true); // true
 
// Custom patterns
Str::is('prd-001*', 'PRD-001-XYZ', true); // true
 
// Email matching
Str::is('JOHN.DOE@example.com', 'john.doe@example.com', true); // true

This enhancement proves particularly valuable in content management systems:

class AssetManager
{
protected array $imageFormats = ['jpg', 'png', 'gif', 'webp'];
 
public function validateAsset(string $filename)
{
foreach ($this->imageFormats as $format) {
if (Str::is("*.{$format}", $filename, true)) {
return true;
}
}
 
return false;
}
 
public function processMediaUploads(array $files)
{
return collect($files)->filter(function ($file) {
// Match media-specific files (e.g., MEDIA-*.*)
return Str::is("MEDIA-*.*", $file, true);
});
}
 
public function categorizeAsset(string $filename)
{
$categories = [
'thumbnail' => 'THUMB-*.*',
'banner' => 'BNR-*.*',
'logo' => 'LOGO-*.*'
];
 
foreach ($categories as $type => $pattern) {
if (Str::is($pattern, $filename, true)) {
return $type;
}
}
 
return 'general';
}
}

The case-insensitive option in Str::is creates more robust pattern matching by eliminating case sensitivity concerns, making applications more user-friendly while maintaining the powerful wildcard functionality.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article