0

我想编写一个 PHP 代码来改变特定字符的值。

例如我有字符串 $text...

$text = "ababcdcd";

我如何切换它们的值?a = b、b = a、c = d 和 d = c 的值。输出应该是......

$text = "babadcdc";

我已经尝试过使用 str_replace() 但它只改变了一个字符。请帮帮我,谢谢。

4

3 回答 3

1

strtr是为此而生的。

$text = "ababcdcd";
$tr = array('a' => 'b', 'b' => 'a', 'c' => 'd', 'd' => 'c');
$text = strtr($text, $tr);

echo $text; //Will output babadcdc
于 2013-11-09T06:50:17.220 回答
0

试试这个来得到你想要的答案。(如果你想替换一个特定的词,请使用前面给出的代码)

<?php
$i=0;
$text = "ababcdcd";
$text2=$text;
$text = str_replace(array('a','c'),array('b','d'), $text);
$text2=str_replace(array('b','d'),array('a','c'), $text2);
$text3='';

for($i=0;$i<strlen($text);$i++)
{
if($i%2==0)
{
$text3.=substr($text, $i, 1); 
}
else
{
$text3.=substr($text2, $i, 1);
}
}
echo "<br>".$text3;
?>
于 2013-11-09T06:47:52.243 回答
0

尝试这个:

$text = str_replace(array('a','b','c','d'),array('b','a','d','c'), $text);
于 2013-11-09T06:26:29.077 回答