考虑以下代码......
${"transformation_" . $image_selector}[0] = 'translated to the left and down,';
$trans_1 = str_replace("left", "right", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("right", "left", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("up", "down", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("down", "up", ${"transformation_" . $image_selector}[0]);
echo $trans_1;
我试图将“left”替换为“right”(反之亦然),将“up”替换为“down”(反之亦然)。当{strong>转换为转换为echo
及以上
right
会一直显示为向左翻译
有什么想法吗?
答案 0 :(得分:1)
您始终将原始字符串传递给str_replace()
并覆盖存储结果的相同变量。因此,只有astast替代发生。
${"transformation_" . $image_selector}[0] = 'translated to the left and down,';
$trans_1 = str_replace("left", "right", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("right", "left", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("up", "down", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("down", "up", ${"transformation_" . $image_selector}[0]); // only this is really performed, the rest is overwritten
echo $trans_1;
尝试
echo strtr(${"transformation_" . $image_selector}[0], array(
'left' => 'right',
'right' => 'left',
'up' => 'down',
'down' => 'up'
));
答案 1 :(得分:0)
您需要转换代码:
$trans_1 = str_replace("left", "right", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("right", "left", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("up", "down", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("down", "up", ${"transformation_" . $image_selector}[0];
echo $trans_1;
为:
$trans_1 = str_replace("left", "right", ${"transformation_" . $image_selector}[0]);
$trans_2 = str_replace("right", "left", ${"transformation_" . $image_selector}[0]);
$trans_1 = str_replace("up", "down", ${"transformation_" . $image_selector}[0]);
$trans_2 = str_replace("down", "up", ${"transformation_" . $image_selector}[0];p
echo $trans_1;
echo $trans_2;
$trans_1
会提供输出translated to the right and down
$trans_2
会提供输出translated to the left and up