Find H2 tag in a string and give it a ID

admin

Administrator
Staff member
Searching stackoverflow i've found a answer for my need, but I can't figure out how to use it exactly if someone could give me a hint It would be appreciated !
Here's my need, I'm using wordpress and I would to put automatic ID to <...> tags so I found "mario" who answer this:
<blockquote>
If you have a coherent input like
that, then you can use regular
expressions. In this case it's both
very acceptable and simple:
Code:
$html = preg_replace_callback(&quot;#&lt;(h[1-6])&gt;(.*?)&lt;/\\1&gt;#&quot;, &quot;retitle&quot;, $html);

function retitle($match) {
    list($_unused, $h2, $title) = $match;

    $id = strtolower(strtr($title, &quot; .&quot;, &quot;--&quot;));

    return &quot;&lt;$h2 id='$id'&gt;$title&lt;/$h2&gt;&quot;; }
The id conversion needs a bit more work. And to make the regex more reliable the innter text match pattern
Code:
(.*?)
could be written as
Code:
([^&lt;&gt;]*)
for example.
<a href="https://stackoverflow.com/questions/4987312/h2-tag-auto-id-in-php-string">H2 tag auto ID in php string</a>
</blockquote>
So i've tryed to apply this to my script, but that doesn't work well at all, here is my code
Code:
&lt;?php 
        $html = get_the_content();
        $html = preg_replace_callback(&quot;#&lt;(h[1-6])&gt;(.*?)&lt;/\\1&gt;#&quot;, &quot;retitle&quot;, $html);
        
        function retitle($match) {
            list($_unused, $h2, $title) = $match;
            $id = strtolower(strtr($title, &quot; .&quot;, &quot;--&quot;));
            return &quot;&lt;$h2 id='$id'&gt;$title&lt;/$h2&gt;&quot;;
        }
    
        if(have_posts()) : while(have_posts()) : the_post(); //Vérifie que le contenu existe 
                echo $html;
            endwhile; 
        endif;
    ?&gt;