替换字符串的一部分

时间:2014-02-04 03:18:21

标签: php str-replace

考虑以下代码......

    ${"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会一直显示为向左翻译

有什么想法吗?

2 个答案:

答案 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