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

symfony/string

Object-oriented string handling for PHP with unified support for raw bytes, UTF-8 code points, and grapheme clusters. Provides robust, consistent string manipulation utilities as part of the Symfony ecosystem.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require symfony/string
    

    No configuration is required—just autoload the package.

  2. First Use Case: Convert a string to lowercase and slugify it:

    use Symfony\Component\String\UnicodeString;
    
    $string = new UnicodeString('Hello World!');
    $slug = $string->lower()->slug();
    // Output: 'hello-world'
    
  3. Key Entry Points:

    • UnicodeString: Core class for all string operations.
    • Inflector: For pluralization/singularization (e.g., tracestrace).
    • Slugger: Specialized slug generation (e.g., Café au laitcafe-au-lait).
  4. Where to Look First:


Implementation Patterns

Core Workflows

1. String Transformation Pipeline

Chain methods for common operations:

$string = new UnicodeString('  Hello, WORLD!  ');
$cleaned = $string
    ->trim()
    ->lower()
    ->replace(['world' => 'Laravel'])
    ->slug();
// Output: 'hello-laravel'

2. Unicode-Aware Operations

Handle grapheme clusters (e.g., emojis, combined characters):

$string = new UnicodeString('👨‍👩‍👧‍👦'); // Family emoji (5 graphemes)
$length = $string->count(); // Returns 5, not 1

3. Inflection for Localization

Pluralize/singularize dynamically:

use Symfony\Component\String\Inflector\EnglishInflector;

$inflector = new EnglishInflector();
$singular = $inflector->singularize('traces'); // 'trace'
$plural = $inflector->pluralize('child');    // 'children'

4. Slug Generation

Generate SEO-friendly URLs:

$slug = (new UnicodeString('Café au lait!'))
    ->slug('en', '_'); // 'cafe_au_lait'

5. Validation and Sanitization

Strip tags, escape HTML, or validate formats:

$clean = (new UnicodeString('<script>alert(1)</script>'))
    ->stripTags();
// Output: ''

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding: Bind UnicodeString as a singleton for global use:

    use Symfony\Component\String\UnicodeString;
    
    public function register()
    {
        $this->app->singleton(UnicodeString::class, function () {
            return new UnicodeString('');
        });
    }
    
  2. Form Request Sanitization: Use in FormRequest validation:

    public function rules()
    {
        return [
            'title' => 'required|string|max:255',
            'slug' => 'required|string|unique:posts',
        ];
    }
    
    public function prepareForValidation()
    {
        $this->merge([
            'slug' => UnicodeString::fromString($this->title)->slug(),
        ]);
    }
    
  3. Model Observers: Auto-slugify titles on save:

    use Illuminate\Database\Eloquent\Model;
    use Symfony\Component\String\UnicodeString;
    
    class Post extends Model
    {
        protected static function booted()
        {
            static::saving(function ($post) {
                if (empty($post->slug)) {
                    $post->slug = UnicodeString::fromString($post->title)->slug();
                }
            });
        }
    }
    
  4. Blade Directives: Create custom Blade helpers:

    Blade::directive('slug', function ($expression) {
        return "<?php echo \\Symfony\\Component\\String\\UnicodeString::fromString({$expression})->slug(); ?>";
    });
    

    Usage:

    <h1>{{ slug($post->title) }}</h1>
    

Performance Optimization

  • Cache Inflectors: Reuse Inflector instances (they’re stateless but heavy to instantiate).
  • Batch Processing: Use UnicodeString::fromString() for bulk operations:
    $strings = ['Hello', 'World'];
    $slugs = array_map(fn ($s) => UnicodeString::fromString($s)->slug(), $strings);
    

Testing

  • Assertions: Use UnicodeString in PHPUnit tests:
    $this->assertEquals(
        'hello-world',
        UnicodeString::fromString('Hello World')->slug()
    );
    
  • Unicode Edge Cases: Test grapheme clusters, emojis, and non-Latin scripts:
    $this->assertEquals(2, UnicodeString::fromString('👨‍👩‍👧‍👦')->count());
    

Gotchas and Tips

Pitfalls

  1. UTF-8 Assumption:

    • The package assumes UTF-8 encoded strings. Passing non-UTF-8 data (e.g., ISO-8859-1) may cause unexpected behavior.
    • Fix: Encode strings explicitly:
      $string = UnicodeString::fromString(mb_convert_encoding($rawString, 'UTF-8'));
      
  2. Grapheme Cluster Quirks:

    • Methods like count() or substring() treat grapheme clusters (e.g., emojis with skin tones) as single units. This may differ from byte-based expectations.
    • Example:
      $string = UnicodeString::fromString('A👨‍👩‍👧‍👦B');
      $string->count(); // 3 (A, emoji, B), not 6
      
  3. Case-Insensitive Methods:

    • startsWith()/endsWith() are case-sensitive by default. Use lower()/upper() first if needed:
      $string = UnicodeString::fromString('Hello');
      $string->startsWith('h'); // false
      $string->lower()->startsWith('h'); // true
      
  4. Deprecated __sleep/__wakeup:

    • Avoid implementing these methods in custom UnicodeString subclasses (deprecated since Symfony 7.4). Use __serialize()/__unserialize() instead.
  5. Slugger Locale Dependencies:

    • Slug generation relies on locale-specific rules (e.g., slug('en') vs. slug('es')). Omit the locale for default behavior:
      $string->slug(); // Uses default locale
      
  6. Performance with Large Strings:

    • Methods like replace() or trim() may be slow for very long strings (e.g., >1MB). Consider preprocessing or chunking:
      $string->chunk(1000)->map(fn ($chunk) => $chunk->slug());
      

Debugging Tips

  1. Inspect String Data: Use toString(), toBytes(), or toGraphemeClusters() to debug:

    $string = UnicodeString::fromString('Café');
    $string->toBytes(); // [0x43, 0x61, 0xC3, 0xA9]
    $string->toGraphemeClusters(); // ['C', 'a', 'f', 'é']
    
  2. Enable Strict Typing: Enable PHP’s strict types to catch type-related issues early:

    declare(strict_types=1);
    
  3. Check for Zero-Width Characters: Methods like startsWith() may fail on strings ending with zero-width characters (e.g., \u{200B}). Trim or normalize first:

    $string = UnicodeString::fromString("Hello\u{200B}");
    $string->trim()->startsWith('H'); // true
    

Extension Points

  1. Custom Inflectors: Extend AbstractInflector for domain-specific rules:

    use Symfony\Component\String\Inflector\AbstractInflector;
    
    class CustomInflector extends AbstractInflector
    {
        protected function getRules(): array
        {
            return [
                'plural' => [
                    'rule' => '/(quiz)$/i',
                    'replacement' => '$1zes',
                ],
            ];
        }
    }
    
  2. Subclassing UnicodeString: Create domain-specific string handlers:

    class DomainString extends UnicodeString
    {
        public function to
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope