php - 使用 str_replace 和数组切换文本

标签 php string

这是我刚刚发现的关于 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.

See it in action .

使用 str_replace 会发生什么,正如您已经发现的那样,第一个 ASCDESC 替换,然后是 DESC 被替换回 ASC,总计什么都没做。

关于php - 使用 str_replace 和数组切换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8452843/

相关文章:

php - 在服务器端(PHP)还是客户端(Javascript)检测移动浏览器更好/更快?

php - 无法添加或更新子行

java - 创建一个单独的对象并从 Java 中的对象引用编辑它

c# - 如果关键字之前存在数字,则删除子字符串

Bash 4.3.33 中的字符串替换(小写)- 错误替换错误

php - Array_merge 与 +

PHP,获取 $_GET 以忽略来自 url 的数字

php - Symfony 功能测试 : how to understand why the test fails (with a 500 Error)

string - 查找没有后缀数组或后缀树的最长重复子字符串

c - 重温 C 中的字符串数组初始化