preg_replace with Regex to add a tag

Asked

Viewed 220 times

2

Does anyone know how to make regex select the phrase and add a tag?

<li>
  <p>b) texto muito longo;</p>
</li>


$FechasemClassAlinea = '<p>[a-z])_.*</p>\n</li>$';

$FechacomClassAlinea = '<p>[a-z])_.*</p>\n</li>\n</ol>$';

echo preg_replace($FechasemClassAlinea, $FechacomClassAlinea, $documento);

I would like you to return this value:

  <li>
    <p>b) texto muito longo;</p>
  </li>
</ol>

2 answers

2


preg_replace('/(<p>[a-z]\).*<\/p>\s*<\/li>)/', '$1'."\n</ol>", $documento);

Explaining:

In the function preg_replace the first parameter is the regex that must start and end with bar / inside the regex it is necessary to escape the characters that have a special meaning in regex as ) and / in this case by adding an inverted bar before the character, s represents space characters/tab/new line etc, should be used in place of the n you placed, finally we put everything in parentheses () to create a group, because this part should continue after the replacement.

In the second parameter we put what will replace the selected text in regex, in which case we should keep the selected group in regex, to catch a group should use $ followed by the group number in ascending order starting with 1, and at the end concatenate the tag that will be added.

  • Thanks man, it worked!!!

0

I managed to accomplish what I wanted with jquery

this is the code

$('p').filter(function(){return $(this).text().match(/^[a-z]\)\s/) }).parent().addClass( "alinea");

Browser other questions tagged

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