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 configuration required—just autoload via Composer.
First Use Case: Replace native PHP string functions with clearer, more expressive helpers. For example:
use Str\Str;
$text = Str::of(' Hello World ')
->trim()
->lower()
->replace(' ', '-')
->value(); // Returns 'hello-world'
Where to Look First:
Str::of() (fluent interface) and static helpers like Str::slug(), Str::title(), or Str::ascii().src/Str namespace for method signatures and examples. No external docs needed—code is self-documenting.Fluent Chain (OOP-style):
$cleaned = Str::of($userInput)
->trim()
->slug()
->prepend('post-')
->value();
Use when: Transforming strings in a single operation with intermediate steps.
Static Helpers (Procedural-style):
$title = Str::title('hello world'); // "Hello World"
$slug = Str::slug('Laravel News'); // "laravel-news"
Use when: One-off transformations or in non-OOP contexts (e.g., Blade templates).
Input Sanitization:
$safeInput = Str::of(request('name'))
->trim()
->ascii()
->value();
Why: Combines trimming, ASCII conversion, and safety in one chain.
URL/Slug Generation:
$slug = Str::of($postTitle)
->slug()
->lower()
->value();
Tip: Chain with Str::kebab() for alternative separators.
Text Wrapping:
$wrapped = Str::of($longText)
->wrap(80, "\n")
->value();
Use case: Preparing CLI output or formatted emails.
Case Conversion:
$snakeCase = Str::of('HelloWorld')
->snake()
->value(); // "hello_world"
Pair with: Laravel’s snake_case conventions for consistency.
Service Providers:
Bind Str as a singleton for global access:
$this->app->singleton('str', fn() => new Str\Str());
Then inject via constructor:
public function __construct(private Str\Str $str) {}
Blade Directives: Create a custom Blade helper:
Blade::directive('str', function ($expression) {
return "<?php echo app('str')->of({$expression})->value(); ?>";
});
Usage:
@str($user->name) <!-- Renders trimmed/lowercased name -->
Form Requests:
Sanitize inputs in prepareForValidation:
public function prepareForValidation()
{
$this->merge([
'name' => Str::of($this->name)->trim()->value(),
]);
}
Null Handling:
Str::of(null) returns an empty Str instance (safe).null won’t throw errors, but value() returns null. Explicitly check with isEmpty() if needed:
if (Str::of($var)->isEmpty()) { ... }
Encoding Assumptions:
ascii() or slug() assume UTF-8 input. For non-UTF-8 strings, normalize first:
$normalized = mb_convert_encoding($str, 'UTF-8');
Str::of($normalized)->slug();
Method Chaining Order:
replace()) are stateful. Order matters:
// Wrong: Replaces after trimming (may miss leading/trailing spaces)
Str::of(' foo ')->replace(' ', '')->trim();
// Correct: Trim first
Str::of(' foo ')->trim()->replace(' ', '');
Performance:
// Less efficient:
Str::of($str)->upper()->lower()->value(); // Redundant
// Better:
Str::of($str)->value(); // Just return as-is
Inspect Intermediate States:
Use ->__toString() for debugging:
$str = Str::of('Test')
->upper()
->__toString(); // "TEST" (visible in logs/dd())
Common Errors:
Call to undefined method: Ensure you’re using Str::of() (not new Str() directly).Argument 1 passed to Str::of() must be string: Pass null or empty strings explicitly:
Str::of($maybeNull ?? '');
Custom Methods: Extend the class via traits or inheritance:
use Str\Str;
class CustomStr extends Str {
public function customMethod()
{
return $this->prepend('custom-');
}
}
Add to Laravel’s Str Facade:
Override Laravel’s Str facade to use this package:
// config/app.php
'aliases' => [
'Str' => Str\Str::class,
];
Caveat: This replaces Laravel’s native Str helpers. Use cautiously.
Testing:
Mock Str in tests for isolated string logic:
$this->partialMock(Str\Str::class, ['slug'])
->shouldReceive('slug')
->andReturn('mocked-slug');
title() or slug() rely on PHP’s default locale. Set it globally if needed:
setlocale(LC_ALL, 'en_US.UTF-8');
Compose with Collections:
Apply Str to Laravel Collections:
$titles = $posts->pluck('title')->map(fn($title) => Str::of($title)->title());
Reverse Engineering:
Use Str::of($str)->getValueObject() to inspect the underlying string object (for advanced use cases).
Performance Benchmark: Compare against native PHP for critical paths:
// Benchmark Str::slug() vs. custom function
$str = 'Laravel 10';
$time = microtime(true);
Str::of($str)->slug();
echo microtime(true) - $time; // ~0.0001s
IDE Support:
Enable PHPStan or Psalm for static analysis of Str method chains to catch type issues early.
How can I help you explore Laravel packages today?