-3

Possible Duplicate:
RegEx match open tags except XHTML self-contained tags
How to parse and process HTML with PHP?
Simple: How to replace “all between” with php?

I am looking for a way to change all the text in an anchor tag that contains certain text in php

ie:

<a href="stackoverflow.com"><strong>This is text</strong></a>

I want to seach for 'This is text' and then replace the anchor tags that the text is in with with something else.

Is it easiest to do with regular expressions?

Thanks

4

2 回答 2

1

Html 可以像 xml 一样对待。您应该使用 php xml 函数来执行此操作。见http://php.net/manual/en/book.xml.php

于 2012-10-23T00:54:51.667 回答
0

您可以通过以下方式轻松做到这一点DOMXpath

$s =<<<EOM
<a href="stackoverflow.com"><strong>This is text</strong></a>
EOM;

$d = new DOMDocument;
$d->loadHTML($s);
$x = new DOMXPath($d);

foreach ($x->query("//a[contains(strong, 'This is text')]") as $node) {
        $new = $d->createTextNode('Hello world');
        $node->parentNode->replaceChild($new, $node);
}

echo $d->saveHTML();
于 2012-10-23T02:08:24.550 回答