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],  ‘title’ => $headings[2][$i]);
	}
	return $menu;
}

This returns an array in the following format:

Array (
[0] => Array ( [slug] => foo [title] => Foo )
[1] => Array ( [slug] => bar [title] => Bar )
)

The slug is the URN representation. You can easily iterate through this to create the corresponding HTML list.

Leave a Reply