Wednesday, 5 June 2019

How to use PHP to insert HTML tags to string by offsets mantaining a valid HTML?

I'm trying to add HTML tags between words inside a string. The positions where the HTML tags should be written are delimited by an array of offsets, for example:

$positions = array(
   0=>array(1,3)
   1=>array(2,6)
   1=>array(8,10)

)

So that if we wanted to add the next tag "" to the following string

$source="<span>This is</span> only a test for stackoverflow"
$tag="<a>"

the result should be the following:

$output = "<span><a class='1'>Th<a class='2'>i</a></a><a class='2'>s</a></span><a class='2'> i</a>s <a class='3'>on</a>ly a test for stackoverflow"

How can I program the next function:

   $cont=0;
    for ($positions as $position) {
         $tag="<a class='$cont'>"
         $cont++;
         $source=addHTMLtoString($source,$tag,$position);
    }

taking into account that each tag insertion must take into account the carry of the previous tags (also the input string may already contain some html tag) and output must be a valid html?

Do you know any library to do this? Maybe PHP DOMDocument functionalities can be useful? Any idea or help is well received.



from How to use PHP to insert HTML tags to string by offsets mantaining a valid HTML?

No comments:

Post a Comment