php 锚点_使用PHP分配锚点ID

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.

上周, 我向读者发起挑战 ,要求他们创建一个PHP脚本,该脚本可在HTML文档中找到锚点,如果该元素还没有ID,则为该元素分配一个ID。 杰里米·帕里什 ( Jeremy Parrish)加紧了挑战。

PHP (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!

杰里米(Jeremy)做得好!

翻译自: https://davidwalsh.name/assign-anchor-ids-php

php 锚点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值