在同一时间搜索和替换两次

This is my code:

$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);

How can i replace the left to right and the right to left in the same time?

You'll need to use a different value temporarily. In this example I've used "xyz", use something a little more obvious.

  • Replace left with xyz
  • Replace right with left
  • Replace xyz with right

Here's a bit of code, in a loop for easy repetition that should (I haven't tested it) replace the left and right values with each other.

$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;
$search  = array('right', 'left', 'xxx');
$replace = array('xxx', 'right', 'left');
$subject = 'right then left then right';
$return = str_replace($search, $replace, $subject);

returns :

$subject : right then left then right

$return : left then right then left