Php 如何用正则表达式替换多个字符和相同数量的字符?
我有以下消息来源:Php 如何用正则表达式替换多个字符和相同数量的字符?,php,regex,preg-replace,Php,Regex,Preg Replace,我有以下消息来源: <font color="black">0</font><font color="white">1101100001001101</font><font color="black">1</font><font color="white">0110</font> 是否有替换模式(我使用PHP)为匹配组$1生成相同数量的空格 结果应该如下所示: <font color="bla
<font color="black">0</font><font color="white">1101100001001101</font><font color="black">1</font><font color="white">0110</font>
是否有替换模式(我使用PHP)为匹配组$1
生成相同数量的空格
结果应该如下所示:
<font color="black">0</font><font color="white"> </font><font color="black">1</font><font color="white"> </font>
01
(请忽略这一事实。我对正则表达式问题的解决方案比对HTML更感兴趣。)试试这里
<?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;
$test='0110101000010110';
echo preg_replace(“~()([10]*)()~e”,“\\1.str_repeat”(“,strlen(\\2”)。“\\3”,$test);
如果该正则表达式前面有白色“>
,则该正则表达式仅与1
|0
匹配
(?你想这样做吗:不,我只想替换白色的1/0。黑色的1/0应该保持不变。对于纯正则表达式,Related/dupe:这也将替换管道字符|
,在类中不需要它。嗯,匹配也很好,但替换相同数量的字符是个问题。这很好。我只是想知道只有正则表达式才能做到这一点,而不必求助于PHP(str_repeat
。@stema Ta。事实上,我喜欢您在示例中使用断言。
<?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;
$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);
(?<="white">)([10]+)