PHP Regex Parse Headings Page Navigation

April 7th, 2008

I’m using headings in the format:

<hx id=”foo”>Foo</hx>

Instead of keeping track of an internal page menu by hand, it’s easily to dynamically parse the string with a regular expression (assuming you’re using level 3 headers):

function create_page_navigation(&$string)
{
$menu = array();
$pattern = ‘/<h3 id=”(.+)”>(.+)<\/h3>/’;
preg_match_all($pattern, $string, $headings);
$headings_num = count($headings[1]);
for ($i = 0; $i < $headings_num; $i++)
{
$menu[] = array('slug' => $headings[1][$i], […]