Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex php, replace ul li by div

I have this list:

<ul>
    <li class="myclass">blablabla 1</li>
    <li class="myclass">blablabla 2</li>
    <li class="myclass">blablabla 3</li>
</ul>

And I want, with a regex, this:

<div class="newClass">blablabla 1</div>
<div class="newClass">blablabla 2</div>
<div class="newClass">blablabla 3</div>

Replacing only <li> works, with this regex:

$pattern = '#<li class="newClass">(.+)</li>#';
$replacement = '<div class="newClass">$1</div>';
$texte = preg_replace($pattern, $replacement, $texte);

I tried to replace the <ul> too, but it doesn't work:

$pattern = '#<ul>(<li class="myclass">(.+)</li>)*</ul>#';
$replacement = '<div class="newClass">$2</div>';
$texte = preg_replace($pattern, $replacement, $texte);

What is wrong?

like image 223
RenishV8 Avatar asked Mar 20 '26 09:03

RenishV8


1 Answers

Your pattern is almost correct.

$pattern = '#<ul>(<li class="myclass">(.+)</li>)*</ul>#';

Although, there are multiple flaws in your pattern.

  • <ul> will assume that all your <li ... will start with <ul> which is not the case for <li class="myclass">blablabla 2</li>. So, you have to use it with ? and preferrably in a non capturing group.. i.e. (?:<ul>)? and similarly at the end (?:<\/ul>)? (note the escape character)

  • You are not checking for spaces and newlines before/after <li.. which should be changed to (\s*<li class="myclass">(.+)<\/li>\s*)

  • Also, no need to add * after (<li ...>...<\/li>)

Working modification of your pattern would be (?:<(?:ul|ol)>)?(\s*<li class="myclass">(.+)<\/li>\s*)(?:<\/(?:ul|ol)>)?

See demo for more explanation and exploration.

like image 193
karthik manchala Avatar answered Mar 21 '26 23:03

karthik manchala