Optimisation PHP le retour : strtr vs str_replace
lundi 1 novembre 2004 | Webdesign
Pour remplacer des mots précis dans une chaîne de texte il existe plusieurs méthodes. Les plus évidentes sont :
- La fonction strtr associée à un tableau contenant les chaînes à traduire.
- Une simple série de str_replace.
Exemple pratique avec des BBtags :
Le tableau d'éléments à remplacer pour strtr :
$arr=array('[/#]'=>'</span>', '[b]'=>'<b>', '[/b]'=>'</b>', '[i]'=>'<i>', '[/i]'=>'</i>', '[quote]'=>'<blockquote>', '[/quote]'=>'</blockquote>');
Le texte de test bidon :
$texte='In a [b]recent article[/b], former TRG CEO Jeff V. Merkey had offered to pay [i]50K USD for a BSD-licensed[/i] Linux. [quote]Groklaw did a followup on his offer[/quote], to which [#red]Jeff responded by notifying the FBI of Groklaws hate crimes violation[/#]. Merkey doesnt exactly have a great record, either, which is made even more apparent by his recent threats to file suit against Merkey.net for slander and [i]trademark infringement[/i], amongst others. In addition, he has also reported [b]Merkey.net[/b] to the FBIs hate crime department. What could Merkey.net do to get Jeff V. Merkey off their backs ?';
Avec str_replace :
$texte=str_replace('[/#]','</span>',$texte);
$texte=str_replace('[b]','<b>',$texte);
$texte=str_replace('[/b]','</b>',$texte);
$texte=str_replace('[i]','<i>',$texte);
$texte=str_replace('[/i]','</i>',$texte);
$texte=str_replace('[quote]','<blockquote>',$texte);
$texte=str_replace('[/quote]','</blockquote>',$texte);
Avec strtr :
$texte=strtr($texte,$arr);
Résultat sur 10000 itérations (temps en millisecondes) :

Conclusion : str_replace reste la solution la plus performante même si l'écriture est plus longue et moins souple.
Mise à jour : Sur la suggestion de Romain, la solution exploitant des tableaux avec str_replace mérite encore plus d'attention.
str_replace avec tableau :
$pattern = array('[b]', '[/b]', '[i]', '[/i]');
$repl = array('<b>', '</b>', '<i>', '</i>');
$texte = str_replace( $pattern, $repl, $texte);










