php-standard-library/str
Lightweight string utility library for PHP, providing common helpers for formatting, parsing, and safe string handling. Designed as a simple “standard library” add-on with a small API surface and easy composer integration.
Installation:
composer require php-standard-library/str
No additional configuration is needed—Laravel’s autoloader will handle the package.
First Use Case:
Replace repetitive mb_* or native string functions with this package’s methods. For example, in a Laravel controller:
use Str\Str;
// Replace: mb_strtolower(trim($input))
$cleanInput = Str::of(request('username'))
->trim()
->lower()
->value();
Where to Look First:
Str\Str (aliased as Str in the package).of(), trim(), slug(), title(), lower(), upper(), and ascii().Str::of()->...->value()) for readability in Laravel’s service layer.Replace manual sanitization in FormRequest classes:
public function rules()
{
return [
'name' => 'required|string',
'slug' => 'sometimes|string',
];
}
protected function prepareForValidation()
{
$this->merge([
'slug' => Str::of($this->name)->slug()->value(),
]);
}
Create reusable traits or helpers for business logic:
// app/Helpers/StringHelper.php
use Str\Str;
if (!class_exists(StringHelper::class)) {
class StringHelper
{
public static function formatPhone($phone)
{
return Str::of($phone)
->replace(['(', ')', '-', ' '], '')
->prepend('+1')
->value();
}
}
}
Standardize JSON payloads:
return response()->json([
'data' => Str::of($user->name)
->title()
->ascii()
->value(),
]);
Use static methods for one-liners:
<h1>{{ Str::title($post->title) }}</h1>
<a href="{{ route('post', Str::slug($post->title)) }}">{{ $post->title }}</a>
Add computed properties to Eloquent models:
public function getSlugAttribute()
{
return Str::of($this->title)->slug()->value();
}
Service Providers: Bind the package to Laravel’s container for dependency injection:
$this->app->singleton(Str::class, function ($app) {
return new Str\Str();
});
Testing:
Mock Str\Str in unit tests:
$mockStr = Mockery::mock(Str::class);
$mockStr->shouldReceive('of')->andReturnSelf();
$mockStr->shouldReceive('slug')->andReturn('test-slug');
Artisan Commands: Use the package for CLI input handling:
$input = Str::of($this->argument('name'))
->trim()
->value();
Middleware: Sanitize input early in the pipeline:
public function handle($request, Closure $next)
{
$request->merge([
'search' => Str::of($request->search)->trim()->value(),
]);
return $next($request);
}
Null Handling:
Str helper, this package does not auto-convert null to an empty string. Explicitly handle null:
$value = Str::of($nullableInput ?? '')->trim()->value();
Multibyte Edge Cases:
$text = "👨👩👧👦"; // Family emoji (4-byte sequence)
$slug = Str::of($text)->slug()->value(); // May not work as expected
Performance in Loops:
$slugs = collect($posts)->map(fn ($post) => cache()->remember(
"slug-{$post->id}",
now()->addHours(1),
fn () => Str::of($post->title)->slug()->value()
));
Laravel Facade Collisions:
Str facade, alias this package to avoid conflicts:
// config/app.php
'aliases' => [
'StrHelper' => Str\Str::class,
];
Static Method Overload:
Str::slug()) cannot be mocked easily in tests. Prefer the fluent interface for testability.Enable Strict Typing:
Add this to composer.json to catch type issues early:
"config": {
"platform": {
"php": "8.1"
},
"optimize-autoloader": true,
"preferred-install": "dist"
}
Log Intermediate Steps: Debug complex transformations by logging each step:
$str = Str::of($input);
\Log::debug('Trim:', $str->trim()->value());
\Log::debug('Slug:', $str->slug()->value());
Benchmark Against Native PHP:
Compare performance with mb_* functions:
$time = microtime(true);
Str::of($longText)->slug()->value();
$strTime = microtime(true) - $time;
$time = microtime(true);
mb_strtolower(mb_str_slug($longText, '-'));
$mbTime = microtime(true) - $time;
\Log::info('Str vs mb_*:', [$strTime, $mbTime]);
Custom Methods: Extend the class via traits or inheritance:
use Str\Str;
trait CustomStrMethods
{
public function customSlug()
{
return $this->slug()->prepend('custom-');
}
}
class ExtendedStr extends Str
{
use CustomStrMethods;
}
Override Default Behavior:
Replace the default slug() pattern:
$str = new Str\Str();
$str->setSlugPattern('/[^a-z0-9]+/u', '-');
Add Laravel Service Provider: Register a custom instance with default configurations:
$this->app->singleton(Str::class, function ($app) {
$str = new Str\Str();
$str->setDefaultLocale('en_US');
return $str;
});
Composer Scripts:
Auto-refactor legacy code using php-cs-fixer:
"scripts": {
"fix-strings": "php-cs-fixer fix --rules=@PHPStandardLibrary --allow-risky=yes"
}
Locale Sensitivity:
Some methods (e.g., title()) rely on locale-specific rules. Set a default locale if needed:
Str::setDefaultLocale('en_US');
Case Conversion:
lower()/upper() use ICU rules. For ASCII-only operations, use ascii() first:
Str::of('Café')->ascii()->lower()->value(); // 'cafe'
Empty String Handling:
Methods like trim() return an empty string for null or whitespace inputs. Explicitly check if needed:
if (Str::of($input)->trim()->isEmpty()) { ... }
Use with Illuminate\Support\Stringable:
Combine with Laravel’s Stringable for hybrid workflows:
use Illuminate\Support\Stringable;
$str = Stringable::from('Hello World');
$processed = Str::of($str->value())
->slug()
->value();
Artisan Commands: Access the container-bound instance:
$str = app(Str::class);
$input = $str->of($this->argument('name'))->trim()->value();
Testing:
Use Laravel’s Testing facade to assert string transformations:
$this->assertEquals(
'test
How can I help you explore Laravel packages today?