spatie/string
Fluent string handling for PHP. Wrap strings with string() to get a chainable object with helpers like between(), case conversion, concatenation, and array-offset access for reading/updating characters. Lightweight utility by Spatie, installable via Composer.
Wrap any string in a String object using the string() helper function to unlock fluent method chaining. Start with simple transformations like toUpper(), toLower(), or tease() for truncation. Example:
// First use case: Clean and format user input
$input = string(request('bio'))->tease(150)->toLower()->prefix('Bio: ');
// Output: "Bio: Now that there is the Tec-9, a crappy spray gun..."
Key starting points:
string() helper: Entry point for all operations.slugify()->prefix('post-')).slugify(), camelCase(), etc.$string[0] = 'X').Use for cleaning user input, URLs, or database fields:
// Sanitize a URL slug
$slug = string($title)->slugify()->toLower()->replaceFirst(' ', '-');
// Normalize text for search
$searchTerm = string($query)->trim()->toLower()->removeDiacritics();
Extract parts of strings (e.g., filenames, paths, or structured text):
// Parse a filename
$extension = string('document.pdf')->segment('.', 1); // "pdf"
$basename = string('folder/document.pdf')->pop('/'); // "document.pdf"
// Extract between delimiters
$content = string($html)->between('<div>', '</div>')->stripTags();
Build strings conditionally or from templates:
// Dynamic possessive forms
$owner = string($user->name)->possessive(); // "John's" or "Charles'"
// Conditional suffix/prefix
$label = string('error')
->when($isWarning, fn($s) => $s->replace('error', 'warning'))
->suffix(': ' . $message);
Combine with Laravel’s helpers or Eloquent:
// Format model attributes
$post->title = string($post->title)->titleCase()->limit(50);
// Use in Blade templates
{{ string($user->bio)->tease(100) }}
Process collections of strings efficiently:
$titles = $posts->pluck('title');
$slugs = $titles->map(fn($title) => string($title)->slugify());
isEmail() return booleans, not String objects. Cache results if chaining:
$isValid = string($email)->isEmail(); // Boolean, not chainable
possessive() throws an error on empty strings. Validate first:
if (string($input)->isEmpty()) return null;
segment()/pop() treat delimiters literally. Escape special chars if needed:
string('path/to/file')->pop('/'); // Works
string('path\to\file')->pop('\'); // May fail; escape backslashes.
contains() is case-sensitive by default. Use toLower() first if needed:
string($text)->toLower()->contains('keyword');
->value() to debug:
$step1 = string($text)->replaceFirst('foo', 'bar')->value();
trim() or stripTags() if strings behave unexpectedly.underscore-php (e.g., camelCase() vs. camel_case()).String class or use traits:
use Spatie\String\String;
class CustomString extends String {
public function reverse(): self {
return new static(strrev($this->value));
}
}
macro():
String::macro('titleize', function() {
return $this->titleCase()->prefix('The ');
});
// Usage: string('laravel')->titleize();
String object. Cache intermediate results:
$cleaned = string($text)->trim()->toLower(); // Better than chaining 10 methods.
map()/each() for collections to minimize object creation.anahkiasen/underscore-php (auto-installed via spatie/string).match() (from Underscore) may behave differently in PHP 8 due to named arguments.assertEquals() with ->value():
$this->assertEquals('MIDDLE', string('StartMiddleEnd')->between('Start', 'End')->toUpper()->value());
string('café')->slugify()).How can I help you explore Laravel packages today?