2015-08-23 95 views
0

我试图用一个字符串替换两个单词,而忽略他们的情况,但我似乎无法找到一种方法来使其正确工作。请看看我的代码:替换两个单词,而忽略大小写,PHP

$text = "you and me"; 

$text = str_ireplace("you","me",$text); 
//$text is "me and me"; 
$text = str_ireplace("me","you",$text); 
//$text is "you and you"; 

预期结果:“我和你”;

实际结果:“你和你”;

编辑:实际不包括忽略情况。

+1

我认为这个问题是不是复制,因为笔者需要区分大小写的搜索,反正我添加了一个答案相关的问题。 –

回答

2

这很简单,只要使用str_ireplace

$text = "YoU and mE"; 
$from = array('you', 'me', '__TMP__'); 
$to = array('__TMP__', 'you', 'me'); 
$text = str_ireplace($from, $to, $text); 
+0

这会忽略像str_ireplace这样的情况吗? – jessica

+0

它给了我一个互联网网络错误。 – jessica

+0

@jessica我更新了示例 –

0

检查:http://php.net/manual/en/function.strtr.php

$trans = array("you" => "me", "me" => "you"); 
echo strtr("you and me", $trans); 
+0

这对于多字符串字符串不起作用。 –

+0

你是对的,这应该是你的朋友 str_ireplace(array_keys($ replace_pairs),array_values($ replace_pairs),$ str); – Armand