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 @supports]()
Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS. What we end up doing is repeating the same properties multiple times with each browser prefix. Yuck. Another thing we...
![Responsive and Infinitely Scalable JS Animations]()
Back in late 2012 it was not easy to find open source projects using requestAnimationFrame()
- this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...
![Geolocation API]()
One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...
![Image Protection Using PHP, the GD Library, JavaScript, and XHTML]()
Warning: The demo for this post may brick your browser.
A while back I posted a MooTools plugin called dwProtector that aimed to make image theft more difficult -- NOT PREVENT IT COMPLETELY -- but make it more difficult for the rookie to average user...