Home > Software design >  Add individual ID to every occurrence of h2 in var
Add individual ID to every occurrence of h2 in var

Time:09-23

I have a $text string with the formatted html inside:

<h2>heading 1</h2>
<p>something</p>
<h2>heading 2</h2>
<p>something</p>
<h2>heading 3</h2>
<p>something</p>

I want to add now an individual id to every h2 heading:

<h2 id="1">heading 1</h2>
<p>something</p>
<h2 id="2">heading 2</h2>

etc.

How can I do this automatically in PHP? I think I need to loop it and plus an $i. I tried str_replace, but I think it isn't the right approach!

$text = str_replace("<h2>", '<h2 id=\"$i\">', $text);

Any hints? Thanks!

CodePudding user response:

this solution will use strpos to loop on all matches and preg_replace because it allows us to limit the number of replaces :

    public  function setTagsId(String $string)
    {
       $i = 0;
        while (strpos($string, '<h2>') !== false)
        {
            $string = preg_replace('/<h2>/', '<h2 id='.$i  .'>', $string, 1);
        }
        return $string;
    }

$string = "<h2>heading 1</h2>
<p>something</p>
<h2>heading 2</h2>
<p>something</p>
<h2>heading 3</h2>
<p>something</p>";

echo setTagsId($string);
  •  Tags:  
  • php
  • Related