【问题标题】:Combine several mb_ereg_replace()-calls结合几个 mb_ereg_replace() 调用
【发布时间】:2023-03-13 22:56:02
【问题描述】:

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

$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

【问题讨论】:

  • 您可以将它们列为alternatives
  • 我知道,但我问的是mb_ereg_replace()。如果你能指出一个更好的解决方案,而不仅仅是告诉我不应该使用我没有问过的东西,我会很高兴,@Truth。
  • @Truth: mb_ereg 不是。 (同样被弃用并不意味着它可以很快被移除。)
  • @mario,我知道如何将前两者结合起来作为替代方案。但是第三个呢,它不会用一个空格替换匹配项。
  • @fragmentedreality:preg_replace() 怎么样?

标签: php regex multibyte-functions


【解决方案1】:

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

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

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

【讨论】:

  • 抱歉,这给了我:style=" d i r e c t i o n : r t l ; " - 来自第二个preg_replace()
  • $direction 是“rtl”或“ltr”,$style 是一个 css 指令。在最好的情况下它是空的,在最坏的情况下它包含包括direction: rtl; 在内的东西你可以从$style = "direction: ltr:"; $direction = "rtl"; 开始。这就是函数中的全部内容。
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2021-02-18
  • 2019-09-15
  • 2016-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多