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

  • By
    5 Awesome New Mozilla Technologies You&#8217;ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    AJAX For Evil:  Spyjax with jQuery

    Last year I wrote a popular post titled AJAX For Evil: Spyjax when I described a technique called "Spyjax": Spyjax, as I know it, is taking information from the user's computer for your own use — specifically their browsing habits. By using CSS and JavaScript, I...

  • By
    Rotate Elements with CSS Transformations

    I've gone on a million rants about the lack of progress with CSS and how I'm happy that both JavaScript and browser-specific CSS have tried to push web design forward. One of those browser-specific CSS properties we love is CSS transformations. CSS transformations...