开发者

Replace href with link text/name

I have a string in php with many a tags... See below for more clerification

It is like .... bla bla bla bla bla bla

<a href="test.php">link1</a'> hellllo

<a href="test.php">link2</a> hiiiiiiiiii

My problem is I want to replace href i.e test.php with 开发者_如何转开发link1,link2,link3 .... so on.

Kindly help. ' ' are added for show only consider them as proper links


use DOMDocument and friends: http://php.net/manual/en/class.domdocument.php

Something like this, but unsure as it is untested, and I am only going off documentation.

$xml = new DOMDocument();
$xml->loadHTML($input_string);
$link_list = $xml->getElementsByTagName('a');
$link_list_length = $link_list->length;
for ($i = 0; $i < $link_list_length; $i++) {
    $attributes = $link_list->item($i)->attributes;
    $href = $attributes->getNamedItem('href');
    $href->value = $link_list->item($i)->nodeValue;
}
$output_string = $xml->saveHTML();


First off, do not use regular expressions. It might work for a bit, but down that path lies madness.

What you want to do is parse the string into XML using PHP's "DOM" library. This converts the HTML (assuming it is valid HTML and not malformed) into a set of objects that you can navigate, modify, and then convert back into a string later.

You can find several guides on the web, like this one.

This is purely off-the-cuff code, I have not tested it, but it should give you a general idea:

$doc = new DOMDocument();
$doc->loadHtml($YOUR_DATA); 
$links = $doc->getElementsByTagName( "a" );
foreach( $links as $link )
{
    // Modify $link however you need to
}
$CONVERTED_DATA = $doc->saveHtml();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜