Question

How can I combine these replacements into one regular expression?

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

The expressions work as expected but I would like to combine them to less then three replace-statements.
I can not just replace the existing direction-attribute, as I don't know if there is any.

edit
added alternation to the first two replacements:

$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
Was it helpful?

Solution

This is the way I'd do it: trim() replaces your 2nd regex (unless you want to keep the linebreaks, if there will be some)

I did it with preg_replace, what you should use instead of ereg_functions (its slightly different, but nothing complex)

$style = trim(preg_replace('~direction:(\\s*?)(rtl|ltr);~','',$style) . " direction: {$direction};");
$style = preg_replace('~(\\s*?){2,}~',' ',$style);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top