Select all elements of an array in a variable with Regex in PHP

2

I would like to make a regex to apply a class to each line with roman number, would the regex be? /(<li>\s*<p>$romanos\)_\-_/ ?

The documents look like this:

<li>
  <p>I - blablabla</p>
</li>
<li>
  <p>II - blablabla</p>
</li>
<li>
  <p>III - blablabla</p>
</li>

I would like it to stay that way

<li class="inciso">
  <p>I - blablabla</p>
</li>
<li class="inciso">
  <p>II - blablabla</p>
</li>
<li class="inciso">
  <p>III - blablabla</p>
</li>

I created an array of Roman numerals

$romanos =  array(I,II,III,IV,V,VI,VII,VIII,IX,X,XI,XII,XIII,XIV,XV,XVI,XVII,XVIII,XIX,XX,XXI,XXII,XXIII,XXIV,XXV,XXVI,XXVII,XXVIII,XXIX,XXX,XXXI,XXXII,XXXIII,XXXIV,XXXV,XXXVI,XXXVII,XXXVIII,XXXIX);

Here are the text variables I'm looking for

$semClassInciso = '/   <li>
  <p>$romanos - /';

Here is the text variable with the LI tag whose class is "subsection

$comClassInciso = '/   <li class="inciso">
  <p>$romanos - /';

Here is the document where the text with the

$documento = file_get_contents($arquivo);

$documento1 = preg_replace($semClassInciso, $comClassInciso , $documento);

echo  $documento1;

In short, I want to add the <li class="inciso"> tag to all occurrences of roman numbers that are at the beginning of a paragraph.

    
asked by anonymous 05.05.2015 / 06:32

1 answer

1

Try to use preg_replace_callback something like this:

<?php

function adicionaTexto($matches) {
    return '<li class="inciso">' . $matches[0];
}

$documento = file_get_contents($arquivo);

$documento1 = preg_replace_callback($semClassInciso, adicionaTexto, $documento);

echo  $documento1;

Well I'll leave the hint of the callback there may be useful. You can also try something like this:

$re = "/(<li>)(\s*<p>[MDCLXVI]+)/"; 
$str = "<li>
  <p>I - blablabla</p>
</li>
<li>
  <p>II - blablabla</p>
</li>
<li>
  <p>III - blablabla</p>
</li>";


$subst = "<li class=\"inciso\">$2"; 

$result = preg_replace($re, $subst, $str);

An example here - > link

    
05.05.2015 / 14:09