-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

6
  • I use preg_replace to search and replace but I don't know how to start at the <a and end at the </a> Commented Oct 23, 2012 at 0:44
  • 2
    Vitally important reading for anyone wishing to parse HTML with regex - stackoverflow.com/questions/1732348/… Commented Oct 23, 2012 at 0:48
  • 1
    Possible duplicates: 1, 2, 3 Commented Oct 23, 2012 at 0:48
  • 1
    DOM parsers. They exist. Use them. Commented Oct 23, 2012 at 0:54
  • 1
    Easiest way might be to use placeholders, e.g., <!-- start text -->, <!-- end text --> and search for those. Also, it might be overkill, but you could also use DOM to ensure you're actually replacing the right thing: php.net/manual/en/domdocument.loadhtml.php Commented Oct 23, 2012 at 1:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.