-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

Community
  • 1
  • 1
milan
  • 2,179
  • 9
  • 24
  • 34
  • I use preg_replace to search and replace but I don't know how to start at the – milan Oct 23 '12 at 00:44
  • 2
    Vitally important reading for anyone wishing to parse HTML with regex - http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – El Yobo Oct 23 '12 at 00:48
  • 1
    Possible duplicates: [1](http://stackoverflow.com/questions/4465620/php-replace-between-tags), [2](http://stackoverflow.com/questions/4411542/preg-replace-data-between-html-tags), [3](http://stackoverflow.com/questions/9641517/php-regex-remove-text-between-tags) – Kermit Oct 23 '12 at 00:48
  • It's either easiest to do with the tool you know best, or with the easiest tool. – mario Oct 23 '12 at 00:48
  • 1
    DOM parsers. They exist. Use them. –  Oct 23 '12 at 00:54
  • 1
    Easiest way might be to use placeholders, e.g., , and search for those. Also, it might be overkill, but you could also use DOM to ensure you're actually replacing the right thing: http://www.php.net/manual/en/domdocument.loadhtml.php – Blair Oct 23 '12 at 01:00

2 Answers2

1

Html can be treated like xml. You should be using the php xml functions to do this. See http://php.net/manual/en/book.xml.php

iWantSimpleLife
  • 1,944
  • 14
  • 22
0

You can do this easily with 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();
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309