开发者

How do I replace multiple characters with the same number of characters with a regular expression?

开发者 https://www.devze.com 2023-03-08 14:10 出处:网络
I\'ve got the following source: <font color=\"black\">0</font><font color=\"white\">1101100001001101</font><font color=\"black\">1</font><font color=\"white\"&g

I've got the following source:

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

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

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

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

The result should look like this:

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

(And please ignore the fact that I'开发者_Go百科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);


Try this here

<?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;

I use a positive look behind (?<=<font color="white">) to search for the color part. And a positive look ahead (?=.*?<\/font>) for the end.

Then I match the already replaced spaces and put them into group 1 and then the [10].

Then I do a while loop until the pattern do not match anymore and a replace with the already replaces spaces and the new found space.


This regex will only match 1 | 0 if it's preceded with "white">.
the (?<=...) syntax in regex is called positive lookbehind...

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

精彩评论

暂无评论...
验证码 换一张
取 消