Add class to Regex result in preg_replace

Asked

Viewed 56 times

0

I would like to add the class 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 model of the lines of my document:

<li>
  <p>a) longo texto</p>
</li>

2 answers

2


It seems to me that you didn’t understand the function preg_replace, because you passed a regular expression as the second parameter, when you should use the text that should replace what was found.

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

To make your code work you must use a subpater (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);

The explanation of this regular expression can be found in that reply

  • It’s Sanction, I know I haven’t quite figured it out yet, one question, is this $1 the rest of the string found? is that it.

  • $1 refers to the first group of parentheses of the regular expression

1

Use Regex with HTML it’s not a good idea.

Instead you can use the 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');

}
  • Valeuuuuu, but how to do, if I have several lines that change the Indice,a), b), c), d) and so on

  • 1

    $img within the foreach should be $li

  • well noted @Sanction, thanks

  • @Even it is possible to use Xpath for this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.