开发者

How to copy the anchor text and replace the href with using PHP

开发者 https://www.devze.com 2023-04-13 01:34 出处:网络
Hello so i have about 1000 link with anchor text formated like this <a href=\"1_1_3.html\" >my anchor tex开发者_JAVA技巧t1</a>

Hello so i have about 1000 link with anchor text formated like this

<a href="1_1_3.html" >my anchor tex开发者_JAVA技巧t1</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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号