开放的编程资料库

当前位置:我爱分享网 > PHP教程 > 正文

使用 PHP 分配锚 ID

上周,我要求我的读者创建一个 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>

干得好杰里米!

未经允许不得转载:我爱分享网 » 使用 PHP 分配锚 ID

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏