在字符串php中交换两个单词 [英] swap two words in a string php

查看:93
本文介绍了在字符串php中交换两个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个字符串"foo boo foo boo",我想用boo替换所有foo,用foo替换booes.预期输出为"boo foo boo foo".我得到的是"foo foo foo foo foo".如何获得预期的输出而不是当前的输出?

Suppose there's a string "foo boo foo boo" I want to replace all fooes with boo and booes with foo. Expected output is "boo foo boo foo". What I get is "foo foo foo foo". How to get expected output rather than current one?

    $a = "foo boo foo boo";
    echo "$a\n";
    $b = str_replace(array("foo", "boo"), array("boo", "foo"), $a);
    echo "$b\n";
    //expected: "boo foo boo foo"
   //outputs "foo foo foo foo"

推荐答案

使用 strtr

从手册中:

如果给定两个参数,则第二个参数应为array('from'=>'to',...)形式的数组.返回值是一个字符串,其中所有出现的数组键都已被相应的值替换.最长的键将首先尝试.替换子字符串后,将不再搜索其新值.

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的长度不同.但是,当所有键的大小相同时,此功能将是最有效的.

In this case, the keys and the values may have any length, provided that there is no empty key; additionaly, the length of the return value may differ from that of str. However, this function will be the most efficient when all the keys have the same size.

$a = "foo boo foo boo";
echo "$a\n";
$b = strtr($a, array("foo"=>"boo", "boo"=>"foo"));
echo "$b\n"; 

输出

foo boo foo boo
boo foo boo foo

在行动

这篇关于在字符串php中交换两个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆