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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With