Объединить несколько вызовов mb_ereg_replace()-
Как я могу объединить эти замены в одно регулярное выражение?
$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 ответ
Решение
Вот как я бы это сделал: trim() заменяет ваше второе регулярное выражение (если только вы не хотите сохранить разрывы строк, если они будут)
Я сделал это с preg_replace, что вы должны использовать вместо ereg_functions (немного отличается, но ничего сложного)
$style = trim(preg_replace('~direction:(\\s*?)(rtl|ltr);~','',$style) . " direction: {$direction};");
$style = preg_replace('~(\\s*?){2,}~',' ',$style);