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

Strings Laravel Package

yiisoft/strings

Yii Strings provides fast, multibyte-safe string utilities for PHP: StringHelper and NumericHelper, Inflector (pluralize, slug), wildcard pattern matching, and optimized combined regex matching with optional memoization.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require yiisoft/strings
    

    No additional configuration is required—this is a lightweight, dependency-free package.

  2. First Use Case:

    use Yiisoft\Strings\StringHelper;
    
    // Basic string manipulation
    $string = StringHelper::lower('Hello WORLD');
    echo $string; // "hello world"
    
    // Common operations
    $trimmed = StringHelper::trim('  extra spaces  ');
    $slug = StringHelper::slugify('Laravel Assessment');
    
  3. Where to Look First:

    • Class Reference (core methods).
    • Tests for edge-case examples.
    • Focus on StringHelper—this is the sole class in the package.

Implementation Patterns

Core Workflows

  1. String Sanitization:

    // Remove HTML tags
    $clean = StringHelper::stripTags('<p>Hello</p>');
    
    // Escape for HTML
    $escaped = StringHelper::htmlspecialchars('User <script>alert()</script>');
    
  2. Text Transformation:

    // Convert to title case
    $title = StringHelper::titleCase('laravel is awesome');
    
    // Convert to kebab-case
    $kebab = StringHelper::kebabCase('LaravelAssessment');
    
  3. Validation & Checks:

    // Check if string is alphanumeric
    if (StringHelper::isAlphanumeric('abc123')) {
        // ...
    }
    
    // Check if string is a valid email
    if (StringHelper::isEmail('test@example.com')) {
        // ...
    }
    
  4. Localization & Encoding:

    // Convert to ASCII (transliterate)
    $ascii = StringHelper::ascii('Café');
    
    // Normalize Unicode (e.g., NFD form)
    $normalized = StringHelper::normalize('résumé');
    

Integration Tips

  • Laravel Blade: Use in directives or helpers:
    // app/Helpers/StringHelper.php
    if (!class_exists('StringHelper')) {
        require app_path('Helpers/StringHelper.php');
    }
    
    // In Blade: @php echo StringHelper::slugify($title) @endphp
    
  • Form Requests: Sanitize user input:
    public function rules()
    {
        return [
            'name' => ['string', 'filter' => [StringHelper::class, 'slugify']],
        ];
    }
    
  • API Responses: Normalize strings before JSON serialization:
    return response()->json([
        'title' => StringHelper::titleCase($request->title),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Encoding Assumptions:

    • StringHelper::ascii() may not handle all Unicode characters perfectly. Test with non-Latin scripts (e.g., Cyrillic, CJK).
    • Fix: Use StringHelper::transliterate() for broader compatibility.
  2. Case Sensitivity:

    • StringHelper::slugify() is case-sensitive by default. Override with:
      StringHelper::slugify('Laravel', ['lower' => true]);
      
  3. Performance:

    • Heavy operations like normalize() or transliterate() on large datasets (e.g., database bulk updates) can be slow.
    • Fix: Cache results or batch process.
  4. Edge Cases:

    • StringHelper::isEmail() uses a basic regex. For strict validation, combine with Laravel’s ValidatesEmail.
    • Empty strings may cause unexpected behavior in some methods (e.g., stripTags('') returns '', but slugify('') returns '-').

Debugging Tips

  • Method Chaining:

    $result = StringHelper::lower($str)
                        ->slugify()
                        ->trim();
    

    Note: The package doesn’t support chaining natively—use intermediate variables or a helper method.

  • Custom Rules: Extend functionality by creating a wrapper:

    class CustomStringHelper extends StringHelper {
        public static function customSlugify($string): string {
            return parent::slugify($string, ['replacement' => '-', 'lower' => true]);
        }
    }
    

Extension Points

  1. Add Custom Replacements:

    $customReplacements = [
        'foo' => 'bar',
        'baz' => 'qux',
    ];
    StringHelper::slugify($str, ['replacements' => $customReplacements]);
    
  2. Override Default Config: The package uses static methods, so "configuration" is passed via method arguments. For reusable settings, create a config class:

    class StringConfig {
        public static function slugifyOptions(): array {
            return ['replacement' => '_', 'lower' => true];
        }
    }
    // Usage: StringHelper::slugify($str, StringConfig::slugifyOptions())
    
  3. Testing: Mock StringHelper in PHPUnit:

    $this->partialMock(StringHelper::class, ['slugify'])
         ->method('slugify')
         ->willReturn('mocked-slug');
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport