Find the text inside and tags

2019-07-20 12:44发布

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.

4条回答
一纸荒年 Trace。
2楼-- · 2019-07-20 13:14
$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

查看更多
仙女界的扛把子
3楼-- · 2019-07-20 13:15

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

preg_match('/<a[^>]*>(.*?)<\/a>/i', $string, $matches);
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-20 13:32

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.

查看更多
Rolldiameter
5楼-- · 2019-07-20 13:36
登录 后发表回答