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

# Manipulation de chaînes (classe Str)

> Manipulez les chaînes avec la classe Str de Laravel et les Fluent Strings, exemples à l'appui.

## Qu'est-ce que Str

`Illuminate\Support\Str` fournit des méthodes riches pour manipuler les chaînes. Plutôt que d'appeler séparément les fonctions natives PHP, vous manipulez les chaînes via une interface unifiée.

Deux styles :

* **Statique** : `Str::slug($title, '-')` — pour un traitement ponctuel
* **Fluent (chaînage)** : `Str::of($title)->slug('-')->limit(50)` — pour enchaîner plusieurs opérations

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

// Statique
$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>
  Le helper global `str()` équivaut à `Str::of()`. Ex : `str('hello')->upper()`.
</Info>

## Conversion de casse

### `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}
use Illuminate\Support\Str;

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

## Slugs et URLs

### `Str::slug()`

Essentiel pour générer une URL propre.

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

Str::slug('Laravel Framework', '-');
// 'laravel-framework'

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

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

<Tip>
  Les caractères non ASCII (japonais, etc.) peuvent produire un slug vide. Envisagez une bibliothèque de translittération, ou utilisez un ID/horodatage.
</Tip>

### `Str::of()` : slug + validation

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

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

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

## Tronquer

### `Str::limit()`

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

$text = 'Laravel est un framework PHP pour créer des applications web élégantes.';

// 20 caractères ("..." par défaut)
Str::limit($text, 20);
// 'Laravel est un frame...'

// Suffixe personnalisé
Str::limit($text, 20, ' → lire la suite');
// 'Laravel est un frame → lire la suite'

// Ne pas couper un mot
Str::limit('The quick brown fox jumps over the lazy dog', 20, preserveWords: true);
// 'The quick brown fox...'
```

### `Str::words()`

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

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

## Recherche et vérification

### `Str::contains()`

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

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}
use Illuminate\Support\Str;

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

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

Str::is('foo*', 'foobar');
// true

Str::is('*/user/*', '/admin/user/profile');
// true

Str::is('F*', 'foo', ignoreCase: true);
// true
```

## Transformation et remplacement

### `Str::replace()`

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

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}
use Illuminate\Support\Str;

$string = 'Programme de ? à ?';

$result = Str::replaceArray('?', ['9 h', '17 h'], $string);
// 'Programme de 9 h à 17 h'
```

### `Str::replaceMatches()`

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

Str::replaceMatches('/[^0-9]/', '', '(03) 1234-5678');
// '0312345678'

Str::replaceMatches('/\d+/', fn ($matches) => '[' . $matches[0] . ']', '1 abc 2 def 3 ghi');
// '[1] abc [2] def [3] ghi'
```

### `Str::remove()`

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

Str::remove('e', 'Peter Piper picked a peck of pickled peppers.');

Str::remove(['foo', 'bar'], 'foo and bar and baz');
// ' and  and baz'
```

### `Str::squish()`

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

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

## Prefixes / suffixes

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

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

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}
use Illuminate\Support\Str;

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

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

Ajoutent le caractère s'il manque (pas de doublon).

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

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}
use Illuminate\Support\Str;

Str::chopStart('https://laravel.com', 'https://');
// 'laravel.com'

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

Str::chopEnd('UserController.php', '.php');
// 'UserController'
```

## Masquage et sécurité

### `Str::mask()`

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

Str::mask('yamada@example.com', '*', 4);
// 'yama**************'

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

Str::mask('yamada@example.com', '*', 3, 5);
// 'yam*****example.com'
```

### `Str::excerpt()`

Utile pour des extraits de recherche.

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

$text = 'Laravel est un framework PHP pour créer des applications web.';

Str::excerpt($text, 'PHP', ['radius' => 10]);
// '...un framework PHP pour créer...'
```

## Chaînes aléatoires et identifiants

### `Str::random()`

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

Str::random(32);
```

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

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

(string) Str::uuid();
// '550e8400-e29b-41d4-a716-446655440000'

// UUIDv7 (triable par temps)
(string) Str::uuid7();

// ULID
(string) Str::ulid();
// '01ARZ3NDEKTSV4RRFFQ69G5FAV'
```

### `Str::password()`

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

Str::password(12);
```

### `Str::counted()`

Retourne un couple nombre + singulier/pluriel formaté.

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

Str::counted('order', 1);
// '1 order'

Str::counted('order', 1000);
// '1,000 orders'
```

En Fluent :

```php theme={null}
Str::of('order')->counted(3);
// '3 orders'
```

<Tip>
  Pratique pour afficher des libellés « 1 order / 2 orders » en anglais avec formatage numérique automatique.
</Tip>

## Fluent Strings

`Str::of()` ou `str()` retourne un `Stringable`. Convertissez explicitement en chaîne avec `(string)` ou dans un contexte string.

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

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

### Exemples de chaînage

**Slug d'article**

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

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

**Extraire le domaine d'une URL**

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

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

**Assainir une entrée utilisateur**

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

$clean = Str::of($userInput)
    ->squish()
    ->limit(255)
    ->toString();
```

**Class name → chemin de fichier**

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

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

### `when()`

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

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

### `pipe()`

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

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

## Méthodes courantes en Fluent

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

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

$str->length();
$str->upper();
$str->lower();
$str->trim();
$str->slug();
$str->camel();
$str->contains('World');
$str->startsWith('Hello');
$str->endsWith('!');
$str->replace(',', '');
$str->prepend('>>> ');
$str->append(' <<<');
$str->reverse();
$str->wordCount();
```

## Récapitulatif

<AccordionGroup>
  <Accordion title="Méthodes Str fréquentes">
    | Méthode                                 | Usage                |
    | --------------------------------------- | -------------------- |
    | `Str::slug($str)`                       | Slug URL-friendly    |
    | `Str::limit($str, $n)`                  | Tronquer             |
    | `Str::contains($str, $needle)`          | Contient ?           |
    | `Str::startsWith($str, $needle)`        | Commence par ?       |
    | `Str::endsWith($str, $needle)`          | Finit par ?          |
    | `Str::replace($search, $replace, $str)` | Remplacer            |
    | `Str::camel($str)`                      | camelCase            |
    | `Str::snake($str)`                      | snake\_case          |
    | `Str::kebab($str)`                      | kebab-case           |
    | `Str::studly($str)`                     | StudlyCase           |
    | `Str::upper($str)`                      | Majuscules           |
    | `Str::lower($str)`                      | Minuscules           |
    | `Str::squish($str)`                     | Compacte les espaces |
    | `Str::after($str, $search)`             | Après                |
    | `Str::before($str, $search)`            | Avant                |
    | `Str::between($str, $from, $to)`        | Entre                |
    | `Str::mask($str, '*', $index)`          | Masquer              |
    | `Str::random($length)`                  | Aléatoire            |
    | `Str::uuid()`                           | UUID                 |
    | `Str::of($str)`                         | Démarrer un Fluent   |
  </Accordion>

  <Accordion title="Statique vs Fluent (Str::of)">
    **Statique** :

    * 1-2 transformations
    * Code simple

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

    **Fluent** :

    * 3 opérations et plus
    * Contient un `when()`
    * Flux de traitement lisible du haut vers le bas

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

  <Accordion title="Str vs fonctions PHP natives">
    Utilisez `Str` plutôt que `strtolower()`, `substr()`, `str_replace()`, etc. :

    * Support multi-octets sûr (utilise `mb_*` en interne)
    * Chaînage possible
    * Ordre des arguments homogène
    * Style de code cohérent avec Laravel
  </Accordion>
</AccordionGroup>


## Related topics

- [Trait Macroable](/fr/advanced/macroable.md)
- [Trait InteractsWithData](/fr/advanced/interacts-with-data.md)
- [Classe Lottery](/fr/advanced/lottery.md)
- [Classe Fluent](/fr/advanced/fluent.md)
- [Guide de migration de l'ancienne vers la nouvelle structure](/fr/advanced/app-structure-migration.md)
