我该如何替换<使用> =和> < =并替换< = with>和> =与<如果它们在同一个字符串中多次出现?

时间:2013-02-13 17:20:30

标签: php preg-replace str-replace

我正在使用PHP进行此操作。我有一个像这样的字符串: “AND day_1> = day_2 AND day_1< day_3” 我想替换第一个> = with<我想替换第二个<使用> =

换句话说,我想颠倒日期范围逻辑:

“AND day_1> = day_2 AND day_1< day_3”

我想反过来看起来像这样:

“AND day_1< day_2 AND day_1> = day_3”

这是我的代码:

$str = "AND day_1 >= day_2 AND day_1 < day_3";
echo "{$str}<br>";
$old_replace = array(">=", "<=", "<", ">");
$new_replace = array("<", ">", ">=", "<=");
$count = 1;
$str = str_replace($old_replace, $new_replace, $str, $count);
echo $str;

当我尝试使用字符串替换时,它会这样做:

替换前:AND day_1&gt; = day_2 AND day_1&lt; day_3 替换后:AND day_1&lt; == day_2 AND day_1&lt; == day_3

1 个答案:

答案 0 :(得分:2)

试试这个:

$replacements = Array("<="=>">",">="=>"<","<"=>">=",">"=>"<=");
$str = strtr($str,$replacements);