【问题标题】:How do I replace multiple characters with the same number of characters with a regular expression?如何用正则表达式替换具有相同数量字符的多个字符?
【发布时间】:2011-05-27 08:15:16
【问题描述】:

我有以下来源:

<font color="black">0</font><font color="white">1101100001001101</font><font color="black">1</font><font color="white">0110</font>

并且想用空格替换所有 white 10。我可以轻松地将它们与

匹配
/<font color="white">([10]*)</font>/g

是否有替换模式(我正在使用 PHP)为匹配组 $1 生成相同数量的空格?

结果应该是这样的:

<font color="black">0</font><font color="white">                </font><font color="black">1</font><font color="white">    </font>

(请忽略 I'm parsing HTML with regexs 的事实。我对正则表达式问题的解决方案比对 HTML 更感兴趣。)

【问题讨论】:

标签: php regex preg-replace


【解决方案1】:
$test = '<font color="black">0</font><font color="white">1101100001001101</font><font color="black">1</font><font color="white">0110</font>';

echo preg_replace ('~(<font color="white">)([10]*)(</font>)~e', '"\\1" . str_repeat(" ", strlen ("\\2")) . "\\3"', $test);

【讨论】:

  • 效果很好。我只是想知道是否有一种仅使用正则表达式的方法来执行此操作,而无需使用 PHP (str_repeat...)。
  • @stema Ta。实际上,我喜欢您在示例中使用断言。
【解决方案2】:

在这里试试

<?php
$string = '<font color="black">0</font><font color="white">1101100001001101</font><font color="black">1</font><font color="white">0110</font>';
$pattern = '/(?<=<font color="white">)( *?)[10](?=.*?<\/font>)/';
$replacement = '$1 ';
while (preg_match($pattern, $string)) {
        $string = preg_replace($pattern, $replacement, $string);
}
echo $string;

我在(?&lt;=&lt;font color="white"&gt;) 后面使用正面的外观来搜索颜色部分。最后积极展望(?=.*?&lt;\/font&gt;)

然后我匹配已经替换的空格并将它们放入第 1 组,然后是 [10]

然后我做一个while循环,直到模式不再匹配,并用已经替换的空格和新找到的空格替换。

【讨论】:

    【解决方案3】:

    这个正则表达式只会匹配1 | 0 如果前面有 "white"&gt;
    正则表达式中的(?&lt;=...) 语法称为正向回溯...

    (?<="white">)([10]+)
    

    【讨论】:

    • 这也将替换管道字符|,在类中不需要它。
    • 嗯,匹配也很好,但是用相同数量的字符替换是问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多