Edit report at https://bugs.php.net/bug.php?id=65020&edit=1

 ID:                 65020
 Comment by:         clicky at erebot dot net
 Reported by:        dhoepelman at gmail dot com
 Summary:            str_replace with array key => value paris
 Status:             Open
 Type:               Feature/Change Request
 Package:            *General Issues
 Operating System:   Irrelevent
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

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));
?>


Previous Comments:
------------------------------------------------------------------------
[2013-06-12 18:39:19] 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



------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=65020&edit=1

Reply via email to