> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Manipolazione delle stringhe (classe Str)

> Manipolazione delle stringhe con la classe Str di Laravel e Stringable (Fluent Strings), con esempi pratici.

## 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

```php theme={null}
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'
```

<Info>
  L'helper globale `str()` equivale a `Str::of()`. Puoi scrivere `str('hello')->upper()`.
</Info>

## 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()`

```php theme={null}
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()`

```php theme={null}
Str::lower('LARAVEL');         // 'laravel'
Str::upper('laravel');         // 'LARAVEL'
Str::title('hello world');     // 'Hello World'
```

## Slug e URL

### `Str::slug()` — slug URL-friendly

```php theme={null}
use Illuminate\Support\Str;

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

Str::slug('Hello World!', '_');
// 'hello_world'
```

<Tip>
  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.
</Tip>

### Slug e validazione con `Str::of()`

```php theme={null}
$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

```php theme={null}
$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

```php theme={null}
Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');
// 'Perfectly balanced, as >>>'
```

## Ricerca e verifica

### `Str::contains()`

```php theme={null}
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()`

```php theme={null}
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

```php theme={null}
Str::is('foo*', 'foobar');            // true
Str::is('*/user/*', '/admin/user/profile'); // true
Str::is('F*', 'foo', ignoreCase: true);    // true
```

## Sostituzione

### `Str::replace()`

```php theme={null}
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()`

```php theme={null}
$string = 'Orario: da ? a ?';

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

### `Str::replaceMatches()` — regex

```php theme={null}
// 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()`

```php theme={null}
Str::remove('e', 'Peter Piper picked a peck of pickled peppers.');
Str::remove(['foo', 'bar'], 'foo and bar and baz');
```

### `Str::squish()` — normalizza spazi

```php theme={null}
Str::squish('  Laravel   Framework  ');
// 'Laravel Framework'
```

## Prima/dopo

### `Str::before()` / `Str::after()`

```php theme={null}
Str::before('test@example.com', '@');   // 'test'
Str::after('test@example.com', '@');    // 'example.com'

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

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

### `Str::between()`

```php theme={null}
Str::between('[debug] Error occurred in module', '[', ']');
// 'debug'
```

### `Str::start()` / `Str::finish()`

Aggiungono il carattere se non presente (non lo duplicano).

```php theme={null}
Str::start('users/profile', '/');   // '/users/profile'
Str::start('/users/profile', '/');  // '/users/profile'
Str::finish('https://example.com', '/'); // 'https://example.com/'
```

### `Str::chopStart()` / `Str::chopEnd()`

```php theme={null}
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()`

```php theme={null}
Str::mask('mario@example.com', '*', 4);
// 'mari**************'

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

### `Str::excerpt()`

```php theme={null}
$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()`

```php theme={null}
Str::random(32);
```

### `Str::uuid()` / `Str::ulid()`

```php theme={null}
(string) Str::uuid();
(string) Str::uuid7();
(string) Str::ulid();
```

### `Str::password()`

```php theme={null}
Str::password(12);
```

### `Str::counted()` — plurale con numero formattato

```php theme={null}
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.

```php theme={null}
$result = Str::of('  hello world  ')
    ->trim()
    ->title()
    ->append('!')
    ->toString();
// 'Hello World!'
```

### Esempi pratici di concatenazione

**Slug di un articolo di blog**

```php theme={null}
$slug = Str::of('  My New Blog Post: Part 1  ')
    ->trim()
    ->lower()
    ->slug('-')
    ->limit(50);
```

**Estrarre il dominio da un URL**

```php theme={null}
$domain = Str::of('https://www.example.com/path/to/page')
    ->after('//')
    ->before('/')
    ->chopStart('www.');
// 'example.com'
```

**Sanitizzare input utente**

```php theme={null}
$clean = Str::of($userInput)
    ->squish()
    ->limit(255)
    ->toString();
```

**Da classe a file path**

```php theme={null}
$path = Str::of('App\Http\Controllers\UserController')
    ->replace('\\', '/')
    ->append('.php')
    ->toString();
```

### Chain condizionale con `when()`

```php theme={null}
$result = Str::of('Laravel')
    ->when($isUppercase, fn ($str) => $str->upper())
    ->append(' Framework');
```

### `pipe()` — callback arbitrarie

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

## Metodi principali di `Str::of()`

```php theme={null}
$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();
```

## Riepilogo

<AccordionGroup>
  <Accordion title="Metodi Str più usati">
    | Metodo                                            | Uso                       |
    | ------------------------------------------------- | ------------------------- |
    | `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` / `studly` | Cambio di case            |
    | `Str::upper($str)` / `lower`                      | Maiuscolo/minuscolo       |
    | `Str::squish($str)`                               | Normalizza spazi          |
    | `Str::after($str, $s)` / `before` / `between`     | Prima/dopo/in mezzo       |
    | `Str::mask($str, '*', $index)`                    | Maschera                  |
    | `Str::random($length)`                            | Casuale                   |
    | `Str::uuid()`                                     | UUID                      |
    | `Str::of($str)`                                   | Inizia catena fluent      |
  </Accordion>

  <Accordion title="Statici vs Fluent">
    **Statici**: per 1-2 trasformazioni; leggibilità semplice.

    ```php theme={null}
    $slug = Str::slug($title);
    ```

    **Fluent (Str::of)**: per 3+ trasformazioni o con condizioni (`when()`); flusso letto dall'alto verso il basso.

    ```php theme={null}
    $slug = Str::of($title)
        ->trim()
        ->lower()
        ->slug()
        ->limit(50);
    ```
  </Accordion>

  <Accordion title="Str vs funzioni PHP standard">
    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
  </Accordion>
</AccordionGroup>


## Related topics

- [Trait Macroable](/it/advanced/macroable.md)
- [Higher-order messages delle collection](/it/advanced/higher-order-messages.md)
- [Deployment](/it/deployment.md)
- [Classe Lottery](/it/advanced/lottery.md)
- [Trait InteractsWithData](/it/advanced/interacts-with-data.md)
