|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-06-12 18:39 UTC] dhoepelman at gmail dot com
Description: ------------ A common pattern in PHP is to see str_replace being used with array_keys and array_values to replace in a string according to the keys and values of an associative array. See comment of Wes Foster: http://php.net/str_replace#95198 It would be nice if PHP would provide a shorthand function for this, which will probably also provide an speed bonus. Could be implementend as a seperate function or as different arguments, similar to strstr. Test script: --------------- /** * Replace keys of associative array in string with values of associative array * @param string[] $replacing Key => value pairs of replacements * @param string $subject The haystack * @see str_replace() **/ function str_replace_assoc($replacing, $subject) { return str_replace(array_keys($replacing), array_values($replacing), $subject); } // Provides: You should eat pizza, beer, and ice cream every day $phrase = "You should eat fruits, vegetables, and fiber every day."; $replacements = ["fruits" => "pizza", "vegetables" => "beer", "fiber" => "ice cream"]; echo str_replace($replacements, $phrase); Expected result: ---------------- You should eat pizza, beer, and ice cream every day PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 01:00:01 2025 UTC |
Use strtr() instead for that. It supports passing an array and as an added bonus, it won't replace the same text twice [1]. Please note that the order of the arguments for strtr() is different than for str_replace() (see the snippet below and their respective pages on php.net for more information) [1] Short snippet that shows how it impacts the result: <?php function strReplaceAssoc(array $replace, $subject) { return str_replace(array_keys($replace), array_values($replace), $subject); } $pairs = array('foo' => 'bar', 'bar' => 'baz'); // Displays string(17) "My baz for a baz!" var_dump(strReplaceAssoc($pairs, 'My foo for a bar!')); // Displays string(17) "My bar for a baz!" var_dump(strtr('My foo for a bar!', $pairs)); ?>