如何使用正则表达式用相同数量的字符替换多个字符? [英] How do I replace multiple characters with the same number of characters with a regular expression?

查看:66
本文介绍了如何使用正则表达式用相同数量的字符替换多个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来源:

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

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

And would like to replace all white 1 and 0 with spaces. I can match them easily with

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

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

Is there a replace pattern (I'm using PHP) to generate the same number of spaces for the matching group $1?

结果应该是这样的:

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

(请忽略 我在这里用正则表达式解析 HTML .我对正则表达式问题的解决方案比对 HTML 更感兴趣.)

(And please ignore the fact that I'm parsing HTML with regexs here. I'm more interested in the solution to the regex problem than in the HTML.)

推荐答案

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

这篇关于如何使用正则表达式用相同数量的字符替换多个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆