Add the class to the Regex result in preg_replace

0

I would like to add the class incision with regex and preg_replace

echo preg_replace("/<li\>\s*<p\>[a-z]\)\s/", "/<li class=\"inciso\"\>\s*<p\>[a-z]\)\s/", $documento);

This is the template for the lines in my document:

<li>
  <p>a) longo texto</p>
</li>
    
asked by anonymous 05.05.2015 / 15:28

2 answers

2

I do not think you understood how preg_replace work because you passed as second parameter a regular expression, when should use the text that should replace what was found.

In addition you are escaping (with backslash) the > character that has no special function in the regular expression.

To make your code work you should use a subpatern (group delimited with parentheses) and references ($ n where n is a number):

preg_replace('/<li>(\s*<p>[a-z]\)\s)/', '<li class="inciso">$1', $documento);

Explanation of this regular expression can be found in this answer

    
08.05.2015 / 14:12
1

Using Regex with HTML not a good idea .

Instead you can use DOM :

<?php

$dom = new DomDocument;
$dom->loadHTML("<li><p>a) longo texto</p></li>");

$lis = $dom->getElementsByTagName('li');

foreach ($lis as $li) {

    $li->setAttribute('class', 'inciso');

}
    
05.05.2015 / 16:07