Here’s something interesting I’ve just found out regarding str_replace().
In my function I need to make two mysql queries which are the same with the slight change on sorting the result. As an argument I get string containing an order clause, for example ‘surname ASC’ but it could be ‘surname DESC’ as well. Now I wanted to easily switch to the reverse sorting using str_replace and I thought this should do the trick:
str_replace(array('ASC', 'DESC'), array('DESC', 'ASC'), $subject)
In my mind it should change all occurences of ASC with DESC and all occurences of DESC with ASC. Since the string contains only one of the two I should get reversed order clause.
However this is not the case. The output of the above code is the same string.
I did some testing and it tourned out that these calls do what you want them to do:
str_replace('ASC', 'DESC', $subject)
str_replace(array('ASC'), array('DESC'), $subject)
In my opinion this is weird because
array('ASC', 'DESC') != array('DESC', 'ASC')
Why then PHP would consider this as equal? Is there any other way to make this kind of replacement easily?
In this scenario, you can use
strtrlike so:This will work because
See it in action.
With
str_replacewhat happens, as you have already found out, is that firstASCis replaced withDESCand thenDESCis replaced back toASC, for a grand total of nothing done.