Stephane
Stephane

Reputation: 5078

str_replace() making wrong replacement

How is this possible that the str_replace() function below returns biWeekly and not Every Other Week ?

$payFrequency = "biweekly";
$postData['payFrequency'] = str_replace(array('weekly','biweekly','twicemonthly','monthly'),array('Weekly','Every Other Week','Twice a Month','Monthly'), $payFrequency, $cnt);
echo "$cnt {$postData['payFrequency']}\n"; // SHOWS 1 biWeekly 

Upvotes: 0

Views: 158

Answers (4)

deceze
deceze

Reputation: 522085

It replaces the "weekly" in "biweekly" with "Weekly", which afterwards does not match "biweekly" anymore.

Upvotes: 2

Andreas Wong
Andreas Wong

Reputation: 60516

because biweekly contains "weekly" which is your first match in the array

array('weekly','biweekly','twicemonthly','monthly')

Thus it converts that first then return.

You could swap your order of replacements:

$payFrequency = "biweekly";

$postData['payFrequency'] = str_replace(
        array('biweekly','weekly','twicemonthly','monthly'), // biweekly then weekly
        array('Every Other Week','Weekly','Twice a Month','Monthly'), $payFrequency, $cnt
);

echo "$cnt {$postData['payFrequency']}\n";

Upvotes: 1

iehrlich
iehrlich

Reputation: 3592

You should swap first and second items in both arrays.

$payFrequency = "biweekly";
$postData['payFrequency'] = str_replace(array('biweekly','weekly','twicemonthly','monthly'),array('Every Other Week','Weekly','Twice a Month','Monthly'), $payFrequency, $cnt);
echo "$cnt {$postData['payFrequency']}\n"; // SHOWS 1 biWeekly 

this would work.

Upvotes: 2

jeroen
jeroen

Reputation: 91734

str_replace is case-sensitive, so biweekly gets replaced, but biWeekly does not. Use str_ireplace if you want a case-insensitive replace.

Upvotes: 0

Related Questions