0

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

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

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

编辑
为前两个替换添加了替换:

$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
4

1 回答 1

1

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

我用 preg_replace 做的,你应该用什么来代替 ereg_functions(它略有不同,但并不复杂)

$style = trim(preg_replace('~direction:(\\s*?)(rtl|ltr);~','',$style) . " direction: {$direction};");
$style = preg_replace('~(\\s*?){2,}~',' ',$style);
于 2012-04-13T10:57:32.157 回答