Vai al contenuto principale

Cos’è la classe Str

La classe Illuminate\Support\Str offre numerosi metodi per la manipolazione delle stringhe. Invece di chiamare separatamente le funzioni standard di PHP, hai un’interfaccia unificata e intuitiva. Ci sono due stili:
  • Metodi statici: Str::slug($title, '-') — per operazioni singole
  • Stile fluent (concatenazione): Str::of($title)->slug('-')->limit(50) — per concatenare più operazioni
use Illuminate\Support\Str;

// Metodo statico
$slug = Str::slug('My New Blog Post', '-');
// 'my-new-blog-post'

// Fluent (Str::of)
$result = Str::of('  My New Blog Post: Part 1  ')
    ->trim()
    ->slug('-')
    ->limit(30);
// 'my-new-blog-post-part-1'
L’helper globale str() equivale a Str::of(). Puoi scrivere str('hello')->upper().

Conversione tra case

Metodi per convertire tra maiuscolo, minuscolo e varie notazioni. Utili per nomi di colonne e chiavi API.

Str::camel() / Str::snake() / Str::kebab() / Str::studly()

use Illuminate\Support\Str;

// camelCase
Str::camel('foo_bar');        // 'fooBar'
Str::camel('user_profile_id'); // 'userProfileId'

// snake_case
Str::snake('fooBar');         // 'foo_bar'
Str::snake('UserProfile');    // 'user_profile'

// kebab-case
Str::kebab('fooBar');         // 'foo-bar'

// StudlyCase (PascalCase)
Str::studly('foo_bar');       // 'FooBar'
Str::studly('user-profile');  // 'UserProfile'

Str::lower() / Str::upper() / Str::title()

Str::lower('LARAVEL');         // 'laravel'
Str::upper('laravel');         // 'LARAVEL'
Str::title('hello world');     // 'Hello World'

Slug e URL

Str::slug() — slug URL-friendly

use Illuminate\Support\Str;

Str::slug('My New Blog Post', '-');
// 'my-new-blog-post'

Str::slug('Hello World!', '_');
// 'hello_world'
Con testo che contiene caratteri non ASCII lo slug può diventare vuoto. Se ti serve traslitterare, valuta librerie apposite oppure usa ID o timestamp nell’URL.

Slug e validazione con Str::of()

$title = '  My New Blog Post: Part 1!  ';

$slug = Str::of($title)
    ->trim()
    ->slug('-')
    ->limit(50);
// 'my-new-blog-post-part-1'

Troncamento

Str::limit() — troncamento per caratteri

$text = 'Laravel is a PHP framework for building elegant web applications.';

// Trunca a 20 caratteri (aggiunge '...' di default)
Str::limit($text, 20);

// Suffisso personalizzato
Str::limit($text, 20, ' → continua');

// Non spezzare parole
Str::limit('The quick brown fox jumps over the lazy dog', 20, preserveWords: true);
// 'The quick brown fox...'

Str::words() — troncamento per parole

Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// 'Perfectly balanced, as >>>'

Ricerca e verifica

Str::contains()

Str::contains('This is my name', 'my');
// true

Str::contains('This is my name', ['my', 'your']);
// true

Str::contains('This is my name', 'MY', ignoreCase: true);
// true

Str::startsWith() / Str::endsWith()

Str::startsWith('https://laravel.com', 'https://');
Str::startsWith('https://laravel.com', ['https://', 'http://']);

Str::endsWith('photo.jpg', '.jpg');
Str::endsWith('photo.jpg', ['.jpg', '.png', '.gif']);

Str::is() — pattern con wildcard

Str::is('foo*', 'foobar');            // true
Str::is('*/user/*', '/admin/user/profile'); // true
Str::is('F*', 'foo', ignoreCase: true);    // true

Sostituzione

Str::replace()

Str::replace('8.x', '13.x', 'Laravel 8.x');
// 'Laravel 13.x'

Str::replace('laravel', 'Symphony', 'I love Laravel', caseSensitive: false);
// 'I love Symphony'

Str::replaceArray()

$string = 'Orario: da ? a ?';

$result = Str::replaceArray('?', ['9:00', '17:00'], $string);
// 'Orario: da 9:00 a 17:00'

Str::replaceMatches() — regex

// Rimuove tutto tranne le cifre
Str::replaceMatches('/[^0-9]/', '', '(03) 1234-5678');
// '0312345678'

// Sostituzione dinamica con closure
Str::replaceMatches('/\d+/', fn ($matches) => '[' . $matches[0] . ']', '1 mela, 2 pere');
// '[1] mela, [2] pere'

Str::remove()

Str::remove('e', 'Peter Piper picked a peck of pickled peppers.');
Str::remove(['foo', 'bar'], 'foo and bar and baz');

Str::squish() — normalizza spazi

Str::squish('  Laravel   Framework  ');
// 'Laravel Framework'

Prima/dopo

Str::before() / Str::after()

Str::before('[email protected]', '@');   // 'test'
Str::after('[email protected]', '@');    // 'example.com'

Str::afterLast('App\Http\Controllers\UserController', '\\');
// 'UserController'

Str::beforeLast('App\Http\Controllers\UserController', '\\');
// 'App\Http\Controllers'

Str::between()

Str::between('[debug] Error occurred in module', '[', ']');
// 'debug'

Str::start() / Str::finish()

Aggiungono il carattere se non presente (non lo duplicano).
Str::start('users/profile', '/');   // '/users/profile'
Str::start('/users/profile', '/');  // '/users/profile'
Str::finish('https://example.com', '/'); // 'https://example.com/'

Str::chopStart() / Str::chopEnd()

Str::chopStart('https://laravel.com', 'https://'); // 'laravel.com'
Str::chopStart('http://laravel.com', ['https://', 'http://']); // 'laravel.com'
Str::chopEnd('UserController.php', '.php'); // 'UserController'

Mascheramento

Str::mask()

Str::mask('[email protected]', '*', 4);
// 'mari**************'

Str::mask('1234-5678-9012-3456', '*', -4);
// '***************3456'

Str::excerpt()

$text = 'Laravel is a PHP framework for building elegant web applications.';

Str::excerpt($text, 'PHP', ['radius' => 10]);
// '...framework PHP for buil...'

ID e stringhe casuali

Str::random()

Str::random(32);

Str::uuid() / Str::ulid()

(string) Str::uuid();
(string) Str::uuid7();
(string) Str::ulid();

Str::password()

Str::password(12);

Str::counted() — plurale con numero formattato

Str::counted('order', 1);      // '1 order'
Str::counted('order', 1000);   // '1,000 orders'
Str::of('order')->counted(3);  // '3 orders'

Fluent Strings

Con Str::of() o str() ottieni un’istanza Stringable e concateni i metodi.
$result = Str::of('  hello world  ')
    ->trim()
    ->title()
    ->append('!')
    ->toString();
// 'Hello World!'

Esempi pratici di concatenazione

Slug di un articolo di blog
$slug = Str::of('  My New Blog Post: Part 1  ')
    ->trim()
    ->lower()
    ->slug('-')
    ->limit(50);
Estrarre il dominio da un URL
$domain = Str::of('https://www.example.com/path/to/page')
    ->after('//')
    ->before('/')
    ->chopStart('www.');
// 'example.com'
Sanitizzare input utente
$clean = Str::of($userInput)
    ->squish()
    ->limit(255)
    ->toString();
Da classe a file path
$path = Str::of('App\Http\Controllers\UserController')
    ->replace('\\', '/')
    ->append('.php')
    ->toString();

Chain condizionale con when()

$result = Str::of('Laravel')
    ->when($isUppercase, fn ($str) => $str->upper())
    ->append(' Framework');

pipe() — callback arbitrarie

$result = Str::of('my-slug')
    ->pipe(fn ($str) => $str->replace('-', '_'))
    ->upper()
    ->toString();
// 'MY_SLUG'

Metodi principali di Str::of()

$str = Str::of('Hello, World!');

$str->length();
$str->upper();
$str->lower();
$str->trim();
$str->slug();
$str->contains('World');
$str->startsWith('Hello');
$str->endsWith('!');
$str->replace(',', '');
$str->prepend('>>> ');
$str->append(' <<<');
$str->reverse();
$str->wordCount();
MetodoUso
Str::slug($str)Slug URL-friendly
Str::limit($str, $n)Troncamento per caratteri
Str::contains($str, $needle)Contiene la stringa
Str::startsWith($str, $needle)Inizia con
Str::endsWith($str, $needle)Finisce con
Str::replace($search, $replace, $str)Sostituzione
Str::camel($str) / snake / kebab / studlyCambio di case
Str::upper($str) / lowerMaiuscolo/minuscolo
Str::squish($str)Normalizza spazi
Str::after($str, $s) / before / betweenPrima/dopo/in mezzo
Str::mask($str, '*', $index)Maschera
Str::random($length)Casuale
Str::uuid()UUID
Str::of($str)Inizia catena fluent
Statici: per 1-2 trasformazioni; leggibilità semplice.
$slug = Str::slug($title);
Fluent (Str::of): per 3+ trasformazioni o con condizioni (when()); flusso letto dall’alto verso il basso.
$slug = Str::of($title)
    ->trim()
    ->lower()
    ->slug()
    ->limit(50);
Rispetto a strtolower(), substr(), str_replace() ecc., con Str:
  • I caratteri multibyte sono gestiti in sicurezza (internamente mb_*)
  • Puoi concatenare le operazioni
  • Non devi ricordare l’ordine degli argomenti
  • Ottieni uno stile coerente con Laravel
Ultima modifica il 13 luglio 2026