Assign Anchor IDs Using PHP
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!
![CSS vs. JS Animation: Which is Faster?]()
How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps?
This article serves as a point-by-point...
![Regular Expressions for the Rest of Us]()
Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...
![MooTools Fun with Fx.Shake]()
Adding movement to your website is a great way to attract attention to specific elements that you want users to notice. Of course you could use Flash or an animated GIF to achieve the movement effect but graphics can be difficult to maintain. Enter...
![Retrieve Your Gmail Emails Using PHP and IMAP]()
Grabbing emails from your Gmail account using PHP is probably easier than you think. Armed with PHP and its IMAP extension, you can retrieve emails from your Gmail account in no time! Just for fun, I'll be using the MooTools Fx.Accordion plugin...