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
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'
Le helper global str() équivaut à Str::of(). Ex : str('hello')->upper().
Conversion de casse
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()
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.
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'
Les caractères non ASCII (japonais, etc.) peuvent produire un slug vide. Envisagez une bibliothèque de translittération, ou utilisez un ID/horodatage.
Str::of() : slug + validation
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()
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()
use Illuminate\Support\ Str ;
Str :: words ( 'Perfectly balanced, as all things should be.' , 3 , ' >>>' );
// 'Perfectly balanced, as >>>'
Recherche et vérification
Str::contains()
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()
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()
use Illuminate\Support\ Str ;
Str :: is ( 'foo*' , 'foobar' );
// true
Str :: is ( '*/user/*' , '/admin/user/profile' );
// true
Str :: is ( 'F*' , 'foo' , ignoreCase : true );
// true
Str::replace()
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()
use Illuminate\Support\ Str ;
$string = 'Programme de ? à ?' ;
$result = Str :: replaceArray ( '?' , [ '9 h' , '17 h' ], $string );
// 'Programme de 9 h à 17 h'
Str::replaceMatches()
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()
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()
use Illuminate\Support\ Str ;
Str :: squish ( ' Laravel Framework ' );
// 'Laravel Framework'
Prefixes / suffixes
Str::before() / Str::after()
use Illuminate\Support\ Str ;
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()
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).
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()
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()
use Illuminate\Support\ Str ;
Str :: mask ( '[email protected] ' , '*' , 4 );
// 'yama**************'
Str :: mask ( '1234-5678-9012-3456' , '*' , - 4 );
// '***************3456'
Str :: mask ( '[email protected] ' , '*' , 3 , 5 );
// 'yam*****example.com'
Str::excerpt()
Utile pour des extraits de recherche.
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()
use Illuminate\Support\ Str ;
Str :: random ( 32 );
Str::uuid() / Str::ulid()
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()
use Illuminate\Support\ Str ;
Str :: password ( 12 );
Str::counted()
Retourne un couple nombre + singulier/pluriel formaté.
use Illuminate\Support\ Str ;
Str :: counted ( 'order' , 1 );
// '1 order'
Str :: counted ( 'order' , 1000 );
// '1,000 orders'
En Fluent :
Str :: of ( 'order' ) -> counted ( 3 );
// '3 orders'
Pratique pour afficher des libellés « 1 order / 2 orders » en anglais avec formatage numérique automatique.
Fluent Strings
Str::of() ou str() retourne un Stringable. Convertissez explicitement en chaîne avec (string) ou dans un contexte string.
use Illuminate\Support\ Str ;
$result = Str :: of ( ' hello world ' )
-> trim ()
-> title ()
-> append ( '!' )
-> toString ();
// 'Hello World!'
Exemples de chaînage
Slug d’article
use Illuminate\Support\ Str ;
$slug = Str :: of ( ' My New Blog Post: Part 1 ' )
-> trim ()
-> lower ()
-> slug ( '-' )
-> limit ( 50 );
Extraire le domaine d’une URL
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
use Illuminate\Support\ Str ;
$clean = Str :: of ( $userInput )
-> squish ()
-> limit ( 255 )
-> toString ();
Class name → chemin de fichier
use Illuminate\Support\ Str ;
$path = Str :: of ( 'App\Http\Controllers\UserController' )
-> replace ( ' \\ ' , '/' )
-> append ( '.php' )
-> toString ();
// 'App/Http/Controllers/UserController.php'
when()
use Illuminate\Support\ Str ;
$result = Str :: of ( 'Laravel' )
-> when ( $isUppercase , fn ( $str ) => $str -> upper ())
-> append ( ' Framework' );
pipe()
use Illuminate\Support\ Str ;
$result = Str :: of ( 'my-slug' )
-> pipe ( fn ( $str ) => $str -> replace ( '-' , '_' ))
-> upper ()
-> toString ();
// 'MY_SLUG'
Méthodes courantes en Fluent
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
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
Statique vs Fluent (Str::of)
Statique :
1-2 transformations
Code simple
$slug = Str :: slug ( $title );
Fluent :
3 opérations et plus
Contient un when()
Flux de traitement lisible du haut vers le bas
$slug = Str :: of ( $title )
-> trim ()
-> lower ()
-> slug ()
-> limit ( 50 );
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