结合几个mb_ereg_replace() - 调用

时间:2012-04-13 10:20:02

标签: php regex multibyte-functions

如何将这些替换组合成一个正则表达式?

$style = $node->getAttribute("style");
$style = mb_ereg_replace("(direction:[[:space:]]*(rtl|ltr);)", "", $style) . " direction: {$direction};";  // remove existing direction-attribute and add the new one
$style = mb_ereg_replace("(^[[:space:]]*)|([[:space:]]*$)", "", $style); // trim spaces at the end and beginning
$style = mb_ereg_replace("([[:space:]]){2,}", " ", $style); // limit spaces to one at a time
$node->setAttribute("style", $style);

表达式按预期工作,但我想将它们组合成少于三个替换语句 我不能只替换现有的direction属性,因为我不知道是否有。

修改
为前两个替换添加了替换:

$style = mb_ereg_replace("(direction:[[:space:]]*(rtl|ltr);)|(^[[:space:]]*)|([[:space:]]*$)", "", $style) . " direction: {$direction};";  // remove existing direction-attribute and trim spaces at the end and beginning and add the new one
$style = mb_ereg_replace("([[:space:]]){2,}", " ", $style); // limit spaces to one at a time

1 个答案:

答案 0 :(得分:1)

这就是我的方式:trim()替换你的第二个正则表达式(除非你想保留换行符,如果有的话)

我用preg_replace做了,你应该使用什么而不是ereg_functions(它略有不同,但没什么复杂的)

$style = trim(preg_replace('~direction:(\\s*?)(rtl|ltr);~','',$style) . " direction: {$direction};");
$style = preg_replace('~(\\s*?){2,}~',' ',$style);