0

这是我的代码:

$css = ".block{float:right; text-align:right;padding:0 20px 0 0; margin:0 0 0 0;}.block h2{font-size:24px; color:#2b7538; font-weight:normal; text-align:right; padding:10px; margin:10px 0 0 0; text-align:left}.block  p{line-height:30px;margin-top:20px; float:left}";

$search = array("float:left","text-align:left","float:right","text-align:right");
$replace = array("float:right","text-align:right","float:left","text-align:left");

echo str_replace($search, $replace, $css);

如何同时替换从左到右和从右到左?

4

2 回答 2

0

您需要暂时使用不同的值。在这个例子中,我使用了“xyz”,使用一些更明显的东西。

  • 将左替换为 xyz
  • 用左替换右
  • 用右替换 xyz

这是一些代码,在一个循环中以便于重复,应该(我没有测试过)相互替换左右值。

$css = ".block{float:right; text-align:right;padding:0 20px 0 0; margin:0 0 0 0;}.block h2{font-size:24px; color:#2b7538; font-weight:normal; text-align:right; padding:10px; margin:10px 0 0 0; text-align:left}.block  p{line-height:30px;margin-top:20px; float:left}";

$from_to = array(
    'left'  => 'xyz',
    'right' => 'left',
    'xyz'   => 'right'
);

foreach ($from_to as $from => $to)
{

    $search = array("float:" . $from, "text-align:" . $from);
    $replace = array("float:" . $to, "text-align:" . $to);

    $css = str_replace($search, $replace, $css);

}

echo $css;
于 2012-05-14T12:19:33.220 回答
0
$search  = array('right', 'left', 'xxx');
$replace = array('xxx', 'right', 'left');
$subject = 'right then left then right';
$return = str_replace($search, $replace, $subject);

返回:

$subject : 从右到左再到右

$return : 左然后右然后左

于 2012-05-14T12:37:18.360 回答