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!
David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...
My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...
CSS is becoming more and more powerful but in the sense that it allows us to do the little things easily. There have been larger features added like transitions, animations, and transforms, but one feature that goes under the radar is generated content. You saw a...
I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax.
Standard jQuery Element Creation
Looks exactly like writing out...