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

Stringy Laravel Package

voku/stringy

voku/stringy is a PHP string manipulation library with a fluent, chainable API and multibyte/Unicode-safe helpers. It offers common text utilities like trimming, casing, slugging, replacing, and comparisons, aiming for predictable results across encodings.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require voku/stringy
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Voku\\": "vendor/voku/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case Basic string manipulation:

    use Voku\Stringy\Stringy;
    
    $string = new Stringy('Hello, World!');
    echo $string->toLower(); // "hello, world!"
    
  3. Where to Look First

    • API Documentation (if available).
    • vendor/voku/stringy/src/ for core classes.
    • tests/ for usage examples and edge cases.

Implementation Patterns

Common Workflows

  1. Chaining Methods Leverage fluent interface for readability:

    $result = (new Stringy('  PHP  '))
        ->trim()
        ->toLower()
        ->replace('php', 'Laravel')
        ->__toString();
    // "laravel"
    
  2. Multibyte Support Handle Unicode gracefully:

    $string = new Stringy('Café');
    echo $string->length(); // 4 (not 5, as 'é' is a single character)
    
  3. Integration with Laravel

    • Service Provider: Bind Stringy as a singleton:
      $this->app->singleton(Stringy::class, function () {
          return new Stringy('');
      });
      
    • Helper Function: Add to app/Helpers/StringHelper.php:
      if (!function_exists('str')) {
          function str(string $value) {
              return new Stringy($value);
          }
      }
      
      Use in Blade:
      {{ str($user->name)->title()->__toString() }}
      
  4. Batch Processing Process arrays of strings efficiently:

    $strings = ['Hello', 'WORLD', 'Laravel'];
    $processed = array_map(fn($s) => (new Stringy($s))->toLower(), $strings);
    
  5. Validation Integration Combine with Laravel's Validator:

    $validator = Validator::make(['input' => '  test  '], [
        'input' => ['required', function ($attribute, $value, $fail) {
            if ((new Stringy($value))->trim()->isEmpty()) {
                $fail('The field is required.');
            }
        }]
    ]);
    

Gotchas and Tips

Pitfalls

  1. Immutable Operations Methods like toLower() return a new Stringy instance. Use __toString() or get() to retrieve the modified value:

    $string = (new Stringy('HELLO'))->toLower();
    echo $string; // "HELLO" (unchanged)
    echo $string->__toString(); // "hello"
    
  2. Performance with Large Strings Avoid chaining heavy operations (e.g., regex) on massive strings. Prefer:

    $string = new Stringy($largeString);
    $string->replacePattern('/regex/', 'replacement'); // Single operation
    
  3. Locale-Sensitive Methods Methods like toTitleCase() may behave unexpectedly without locale settings. Set explicitly:

    setlocale(LC_ALL, 'en_US.UTF-8');
    $string = (new Stringy('hello world'))->toTitleCase();
    // "Hello World"
    
  4. Edge Cases in split() Empty delimiters or strings may return unexpected results:

    $string = new Stringy('a,b,c');
    $string->split(','); // ['a', 'b', 'c']
    $string->split('');   // ['a', ',', 'b', ',', 'c'] (not ['a,b,c'])
    

Debugging Tips

  1. Inspect Internals Use get() to debug the current state:

    $string = new Stringy('test');
    $string->toUpper();
    dump($string->get()); // "TEST"
    
  2. Check for Multibyte Issues Verify encoding with:

    $string = new Stringy('Café');
    dump(mb_strlen($string->get(), 'UTF-8')); // 4
    
  3. Override Default Behavior Extend Stringy for custom logic:

    class CustomStringy extends Stringy {
        public function customMethod() {
            return $this->replace('foo', 'bar')->toUpper();
        }
    }
    

Extension Points

  1. Custom Methods Add static methods to a helper class:

    class StringHelper {
        public static function slugify(string $string): string {
            return (new Stringy($string))
                ->toLower()
                ->replacePattern('/[^a-z0-9]+/', '-')
                ->trim('-')
                ->__toString();
        }
    }
    
  2. Laravel Macros Extend Stringy globally in a service provider:

    Stringy::macro('truncate', function ($length) {
        return $this->length() > $length
            ? $this->substr(0, $length).'...'
            : $this;
    });
    

    Usage:

    $string = new Stringy('Laravel is awesome');
    echo $string->truncate(10)->__toString(); // "Laravel..."
    
  3. Performance Optimization Cache repeated operations:

    $string = new Stringy('complex string');
    $cached = $string->replacePattern('/pattern/', 'replacement');
    // Reuse $cached instead of re-running the operation
    
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor