Home > Software engineering >  PHP/Regex - How to remove one from what found in a string using preg_replace?
PHP/Regex - How to remove one from what found in a string using preg_replace?

Time:12-04

I have

aa
aaa
aaaa
aaaaa

I want to decrease one unit from what was found in the text. So that the result should be

a
aa
aaa
aaaa

using preg_replace.

How can I do that?

Edit

I'm working on it at https://regex101.com.

Regex

(?:<br \/>){5}

and the text

<p>1<br /><br />2<br /><br /><br />3<br /><br /><br /><br />4<br /><br /><br /><br /><br />5</p>.

I wanted to put it in a loop and remove it from top to bottom. So first, it removes the <br /> that is repeated 5 times then 4 then 3... . But that didn't work!

CodePudding user response:

You mean something like this:

<?php

$data = ['aa',
'aaa',
'aaaa',
'aaaaa',
];

$newdata = [];
foreach ($data as $value) {
    $newdata[] = preg_replace('/(.*).$/', '\1', $value);
}
var_dump($data, $newdata);

CodePudding user response:

You might use a capture group 1 with a repeating backreference in group 2.

In the replacement use group 2, that has 1 occurrence less than that total match.

(<br />)(\1{1,4})
  • (<br />) Capture group 1, match (<br /> (Note that with a delimiter like ~ for the pattern you don't have to escape the backslash)
  • ( Capture group 2
    • \1{1,4} Backreference to group 1, repetead 1-4 times
  • ) Close group 2

Regex demo

$re = '~(<br />)(\1{1,4})~';
$str = '<p>1<br /><br />2<br /><br /><br />3<br /><br /><br /><br />4<br /><br /><br /><br /><br />5</p>';
$result = preg_replace($re, '$2', $str);

echo $result;

echo $result;

Output

<p>1<br />2<br /><br />3<br /><br /><br />4<br /><br /><br /><br />5</p>
  • Related