Q:

H2 tag auto ID in php string

I'm trying to write a wordpress filter that autoparses the content and takes the following:
<h2>lesson 1 bannanas</h2>

and replaces it with
<h2 id="lesson-1-bannanas">lesson 1 bannanas</h2>

So that I can then link people directly to sections of a page or blogpost. How would I do this without resorting to something as heavy as DOMDocument?

A:

If you have a coherent input like that, then you can use regular expressions. In this case it's both very acceptable and simple:
$html = preg_replace_callback("#<(h[1-6])>(.*?)</\\1>#", "retitle", $html);

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

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

    return "<$h2 id='$id'>$title</$h2>";
}

The id conversion needs a bit more work. And to make the regex more reliable the innter text match pattern (.*?) could be written as ([^<>]*) for example.

