这是我刚刚发现的关于 str_replace() 的一些有趣的东西。 在我的函数中,我需要进行两个相同的 mysql 查询,只是在对结果进行排序时稍作更改。作为参数,我得到包含顺序子句的字符串,例如“surname ASC”,但它也可以是“surname DESC”。现在我想使用 str_replace 轻松切换到反向排序,我认为这应该可以解决问题:
str_replace(array('ASC', 'DESC'), array('DESC', 'ASC'), $subject)
在我看来,它应该将所有出现的 ASC 更改为 DESC,并将所有出现的 DESC 更改为 ASC。由于该字符串仅包含两个中的一个,因此我应该得到颠倒顺序的子句。 然而,这种情况并非如此。上面代码的输出是同一个字符串。
我做了一些测试,结果证明这些调用可以执行您希望它们执行的操作:
str_replace('ASC', 'DESC', $subject)
str_replace(array('ASC'), array('DESC'), $subject)
在我看来这很奇怪,因为
array('ASC', 'DESC') != array('DESC', 'ASC')
为什么 PHP 会认为这是相等的?有没有其他方法可以轻松实现这种替换?
最佳答案
在这种情况下,您可以使用 strtr
像这样:
strtr($subject, array('ASC' => 'DESC', 'DESC' => 'ASC'));
这会起作用,因为
If given two arguments, the second should be an array in the form
array('from' => 'to', ...)
. The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
使用 str_replace
会发生什么,正如您已经发现的那样,第一个 ASC
被 DESC
替换,然后是 DESC
被替换回 ASC
,总计什么都没做。
关于php - 使用 str_replace 和数组切换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8452843/