Reputation: 1037
It's more of a clarification than a question, I have this code here:
$itemSizeArray = array(
'S' => 'Small',
'M' => 'Medium',
'L' => 'Large',
'X' => 'XLarge'
);
$modifierSize = 'X';
$submenuModifierDescription['SUME_DESCRIPTION'] = "Small Toppings";
echo str_replace(
$itemSizeArray,
$itemSizeArray[$modifierSize],
$submenuModifierDescription['SUME_DESCRIPTION']
);
It works fine in all cases except when $modifierSize = 'X';
,
It outputs "XXLarge Toppings"
(double X). -- problem
In other cases i.e. when $modifierSize = 'L';
it outputs Large Toppings
. -- no problem
After I read the documentation a bit more I fixed the code with this line
echo str_replace($itemSizeArray['S'], $itemSizeArray[$modifierSize], $submenuModifierDescription['SUME_DESCRIPTION']);
and it works fine, but I did not understand why.
Upvotes: 0
Views: 80
Reputation: 2693
Docs says:
If search is an array and replace is a string, then this replacement string is used for every value of search.
So "Small Toppings" becomes "XLarge Toppings" and then, in string "XLarge Toppings" Large becomes XLarge and result is "XXLarge Toppings".
Here is smaller example to understand what is happening:
$itemSizeArray = array('Small', 'Large');
var_dump(str_replace($itemSizeArray, 'XLarge', "Small Toppings"));exit;
Upvotes: 1
Reputation: 1560
What exactly are you trying to replace and with what in your target string? A reason why it's showing weird behavior might be because str_replace can expect an array of values for both the first (search for) and second (replace with) argument. In your original code sample you were supplying key-value pairs as the needle (first argument).
For example, if you want to search for S, M, L etc. and replace them with Small, Medium, Large etc., you can try the following:
str_replace(array_keys($itemSizeArray), array_values($itemSizeArray), $subject);
Upvotes: 1
Reputation: 2428
I think the correct way to achieve this is
$itemSizeArray = array('S' => 'Small', 'M' => 'Medium', 'L' => 'Large', 'X' => 'XLarge');
$modifierSize = 'X';
$submenuModifierDescription['SUME_DESCRIPTION'] = "Small Toppings";
echo str_replace($submenuModifierDescription['SUME_DESCRIPTION'], $itemSizeArray[$modifierSize], $submenuModifierDescription['SUME_DESCRIPTION']);
But still why complicate things . You can just change every time you need it the value of the menu variable
$submenuModifierDescription['SUME_DESCRIPTION'] = $itemSizeArray[$modifierSize];
Your code returns the weird result in X case because str_replace function first parameter is an array.
Upvotes: 0