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 required—Laravel’s autoloader will handle the package automatically.
First Use Case: Replace repetitive or error-prone string operations in Laravel controllers, services, or Blade templates. For example:
use PhpStandardLibrary\Str;
// Replace native PHP functions
$trimmed = Str::trim(' hello '); // 'hello'
$slug = Str::slug('Hello World'); // 'hello-world'
// Use fluent interface for complex operations
$formatted = Str::of(' USER_NAME ')
->trim()
->lower()
->replace('_', ' ')
->title()
->value(); // 'User Name'
Where to Look First:
Str::of() for fluent operations and static methods like Str::trim(), Str::slug(), Str::title(), and Str::ascii().{{ Str::title($post->title) }}).Replace manual string cleaning in Laravel’s FormRequest classes:
use PhpStandardLibrary\Str;
public function rules()
{
return [
'username' => 'required|string|max:255',
'bio' => 'nullable|string',
];
}
public function prepareForValidation()
{
$this->merge([
'username' => Str::of($this->username)->trim()->lower()->value(),
'bio' => Str::of($this->bio)->trim()->value(),
]);
}
Use accessors/mutators to standardize string outputs:
use PhpStandardLibrary\Str;
class Post extends Model
{
public function getSlugAttribute()
{
return Str::slug($this->title);
}
public function setTitleAttribute($value)
{
$this->attributes['title'] = Str::of($value)->trim()->title()->value();
}
}
Standardize JSON payloads in controllers:
use PhpStandardLibrary\Str;
public function show(Post $post)
{
return response()->json([
'id' => $post->id,
'title' => Str::title($post->title),
'slug' => Str::slug($post->title),
'excerpt' => Str::of($post->body)->limit(200)->append('...')->value(),
]);
}
Register a Blade directive for reusable string operations:
// In AppServiceProvider@boot()
Blade::directive('format', function ($expression) {
return "<?php echo PhpStandardLibrary\Str::of({$expression})->trim()->title()->value(); ?>";
});
Usage in Blade:
<h1>@format($post->title)</h1>
Simplify assertions in PHPUnit/Pest tests:
use PhpStandardLibrary\Str;
it('formats the title correctly', function () {
$title = Str::of(' hello world ')->title()->value();
expect($title)->toBe('Hello World');
});
Chain methods for complex transformations:
$cleaned = Str::of($rawInput)
->trim()
->lower()
->replace(['&', ' ', '.'], '-')
->slug()
->prepend('doc-')
->value();
Str FacadeIf you prefer this package over Laravel’s Str helper, alias it globally:
// In config/app.php
'aliases' => [
'Str' => PhpStandardLibrary\Str::class,
];
Now use Str::slug() instead of Str::of($input)->slug().
Bind the package to a custom interface for dependency injection:
$this->app->bind(
StringFormatter::class,
fn () => new PhpStandardLibrary\Str()
);
Usage:
public function __construct(private StringFormatter $formatter) {}
public function formatTitle(string $input): string
{
return $this->formatter->of($input)->title()->value();
}
Extend the package by creating a wrapper class:
class AppStr extends PhpStandardLibrary\Str
{
public static function customSlug(string $input, string $separator = '-')
{
return parent::of($input)
->trim()
->lower()
->replace([' ', '_'], $separator)
->value();
}
}
Format CLI outputs consistently:
use PhpStandardLibrary\Str;
class GenerateSlugCommand extends Command
{
protected function handle()
{
$slug = Str::slug($this->argument('title'));
$this->info("Generated slug: {$slug}");
}
}
@mixin annotations in PHPStorm for better autocompletion:
/**
* @mixin \PhpStandardLibrary\Str
*/
class Str {}
parameters:
string_formatter: PhpStandardLibrary\Str::class
// Benchmark Str::slug() vs. mb_strtolower() + str_replace()
$text = "Café\u0301"; // "Café" with combining acute accent
$slug = Str::slug($text); // Ensure it handles diacritics correctly
Str::ascii() to normalize Unicode strings if needed.null or non-string inputs. Handle explicitly:
$safeSlug = Str::of($maybeNullInput ?? '')
->slug()
->value();
Str class:
public static function safeSlug(?string $input): string
{
return Str::of($input ?? '')->slug()->value();
}
Str object, but some (like value()) return the result. Chain carefully:
// Wrong: Returns the Str object, not the string
$result = Str::of('test')->value()->upper();
// Correct:
$result = Str::of('test')->upper()->value();
tap() for debugging intermediate steps:
Str::of($input)
->tap(fn ($str) => logger()->debug($str->value()))
->slug();
Str::title() may not handle locale-specific rules (e.g., Turkish dotted 'i'). Test with:
$turkish = "merhaba dünya"; // Turkish "hello world"
$title = Str::title($turkish); // Ensure 'i' is not capitalized as 'İ'
Str::ascii() or implement custom logic.Str to this package, ensure no conflicts with Laravel’s Str facade:
composer show laravel/framework | grep -i str
How can I help you explore Laravel packages today?