Assign Anchor IDs Using PHP

By  on  

Last week, I challenged my readers to create a PHP script that finds anchors in an HTML document and assigns an ID to the element IF the element doesn't have an ID already. Jeremy Parrish stepped up to the challenge.

The PHP

function anchor_fix($anchor)
{
  // the match comes as an array
  // the whole match (what we want) is the 0th element
  if (! preg_match('/\sid="/i', $anchor[0])) {
	 return preg_replace('/name="([^"]*)"/i', 'id="$1" $0', $anchor[0]);
  } else {
	 // already has an id!
	 return $anchor[0];
  }
}

/* usage */
echo preg_replace_callback('/<a[^>]*>/i', 'anchor_fix', file_get_contents('page.html'));

The Result

<body>
	<b>
	<a 
	name="stuff">this is an anchor</a> some text... <a name="another">another one...</a>
	</b>
	<div><a id="thing" name="other">another thing</a>
	</div>
</body>

... becomes ...

<body>
	<b>
	<a 
	id="stuff" name="stuff">this is an anchor</a> some text... <a id="another" name="another">another one...</a>
	</b>
	<div><a id="thing" name="other">another thing</a>
	</div>
</body>

Great job Jeremy!

Recent Features

Incredible Demos

  • By
    Add Site Screenshots for External Links Using MooTools Tooltips

    Before you send your user to an unknown external website, why not provide them a screenshot of the site via a tooltip so they may preview the upcoming page? Here's how you can do just that using MooTools. The MooTools JavaScript The first step is to grab...

  • By
    Introducing MooTools HeatMap

    It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking.  With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and...