上周,我要求我的读者创建一个 PHP 脚本,该脚本在 HTML 文档中查找锚点,并在元素还没有 ID 时为该元素分配一个 ID。杰里米·帕里什 (Jeremy Parrish) 直面挑战。
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'));
结果
<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>
……变成……
<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>
干得好杰里米!