开发者

Find the text inside <a> and </a> tags

I need a very little help to find the content inside certain and tags.

Example:

$string = '<a href="dummyurl">TEXT</a><span>Other Text</span开发者_开发问答>';

I'd like to find 'TEXT' and replace it with some other value. Obviuosly the content of 'href' and 'TEXT' is dynamically generated.


If you're sure there's no > character in the start tag (except for the obvious 1):

preg_match('/<a[^>]*>(.*?)<\/a>/i', $string, $matches);


$doc = new DOMDocument;
$doc->loadHTML('<a href="dummyurl">TEXT</a><span>Other Text</span>');
$anchors = $doc->getElementsByTagName('a');
$len = $anchors->length;
for($i = 0; $i < $len; $i++) {
    if($anchors->item($i)->nodeValue == 'foo') {
        $anchors->item($i)->nodeValue = 'New Value';
        $anchors->item($i)->setAttribute('href', 'new href');
    }
}
$newHTML = $doc->saveHTML();
echo $newHTML;

http://php.net/manual/en/class.domdocument.php


Reference: phppro.org's Get Link Text


Consider learning the DOM, which will enable you to work with both HTML and XML documents and answer questions like this in a generic manner. There is some learning curve, and it will be slower than fine-tuned local regexes, but it'll be more robust as well as applicable to nearly everything that is an HTML or XML document.

PHP has a whole big section on using the DOM in PHP within the manual.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜