Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

String Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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:

  1. string() helper: Entry point for all operations.
  2. Method chaining: Combine operations (e.g., slugify()->prefix('post-')).
  3. Underscore integration: Access 50+ methods via slugify(), camelCase(), etc.
  4. Array access: Modify characters by index (e.g., $string[0] = 'X').

Implementation Patterns

1. Data Sanitization & Normalization

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();

2. Text Extraction & Segmentation

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();

3. Dynamic String Generation

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);

4. Integration with Laravel Ecosystem

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) }}

5. Bulk Operations

Process collections of strings efficiently:

$titles = $posts->pluck('title');
$slugs  = $titles->map(fn($title) => string($title)->slugify());

Gotchas and Tips

Pitfalls

  1. Non-chainable methods: Underscore methods like isEmail() return booleans, not String objects. Cache results if chaining:
    $isValid = string($email)->isEmail(); // Boolean, not chainable
    
  2. Empty string edge cases: possessive() throws an error on empty strings. Validate first:
    if (string($input)->isEmpty()) return null;
    
  3. Delimiter sensitivity: 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.
    
  4. Case sensitivity: contains() is case-sensitive by default. Use toLower() first if needed:
    string($text)->toLower()->contains('keyword');
    

Debugging Tips

  • Inspect intermediate steps: Use ->value() to debug:
    $step1 = string($text)->replaceFirst('foo', 'bar')->value();
    
  • Check for hidden characters: Use trim() or stripTags() if strings behave unexpectedly.
  • Underscore conflicts: If a method isn’t found, verify it’s from underscore-php (e.g., camelCase() vs. camel_case()).

Extension Points

  1. Custom methods: Extend the String class or use traits:
    use Spatie\String\String;
    
    class CustomString extends String {
        public function reverse(): self {
            return new static(strrev($this->value));
        }
    }
    
  2. Macros: Add reusable chains via Laravel’s macro():
    String::macro('titleize', function() {
        return $this->titleCase()->prefix('The ');
    });
    // Usage: string('laravel')->titleize();
    
  3. Underscore overrides: Replace default methods by publishing the package’s config or using a wrapper.

Performance Notes

  • Avoid over-chaining: Each method creates a new String object. Cache intermediate results:
    $cleaned = string($text)->trim()->toLower(); // Better than chaining 10 methods.
    
  • Bulk operations: Use map()/each() for collections to minimize object creation.

Config Quirks

  • Underscore integration: Requires anahkiasen/underscore-php (auto-installed via spatie/string).
  • PHP 8+ only: Methods like match() (from Underscore) may behave differently in PHP 8 due to named arguments.

Testing

  • Assertions: Use assertEquals() with ->value():
    $this->assertEquals('MIDDLE', string('StartMiddleEnd')->between('Start', 'End')->toUpper()->value());
    
  • Edge cases: Test empty strings, Unicode, and special characters (e.g., string('café')->slugify()).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle