[英]How to copy the anchor text and replace the href with using PHP
Hello so i have about 1000 link with anchor text formated like this 您好,我有大约1000个链接的锚文本格式如下
<a href="1_1_3.html" >my anchor text1</a>
<a href="1_4_8.html" >my anchor text2</a>
.... etc ....等
i want to replace all the href link with their own anchor text and add .php at the end of the url 我想用自己的锚文本替换所有href链接,并在网址末尾添加.php
result must be like this : 结果必须是这样的:
<a href="my anchor text1.php" >my anchor text1</a>
<a href="my anchor text2.php" >my anchor text2</a>
Thanks in advance for your time. 在此先感谢您的时间。
$dom = new DOMDocument();
$dom->loadHTML($yourhtml);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $a) {
$href = $a->getAttribute('href');
.... manipulate the href
$a->setAttribute('href', $href);
}
$newhtml = $dom->saveHTML();
$string = '<a href="1_1_3.html" >my anchor text1</a>
<a href="1_4_8.html" >my anchor text2</a>';
$string = preg_replace('#<a href="(.*?)" >(.*?)</a>#is', '<a href="\\2.php" >\\2</a>', $string);
echo $string;
Result: 结果:
<a href="my anchor text1.php" >my anchor text1</a>
<a href="my anchor text2.php" >my anchor text2</a>
Demo: http://ideone.com/k9NOc 演示: http : //ideone.com/k9NOc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.