1

Possible Duplicate:
How to get Anchor text using DomDocument?
Getting node's text in PHP DOM

I have a script that finds all the anchor tags of a certain class in a DOMDocument. I am looking to echo the text that is contained within the <a>"....."</a> tags.

Community
  • 1
  • 1
beatsforthemind
  • 879
  • 2
  • 8
  • 17

2 Answers2

0

You can access DOMText node directly using XPath:

$xpath = new DOMXPath($dom_document);
$node = $xpath->query('//a/text()')->item(0);
echo $node->textContent; // text
pckabeer
  • 686
  • 6
  • 27
-2

You can use preg_match(). Here is an example:

$link = '<a href="http://www.coursesweb.net" title="www.CoursesWeb.net">www.CoursesWeb.net</a>';
if(preg_match('/\<a([^\>]*)\>(.*?)\<\/a\>/i', $link, $mc)) {
  echo $mc[2];         // www.CoursesWeb.net
}
CoursesWeb
  • 4,179
  • 3
  • 21
  • 27
  • Please refrain from parsing HTML with RegEx as it will [drive you į̷̷͚̤̤̖̱̦͍͗̒̈̅̄̎n̨͖͓̹͍͎͔͈̝̲͐ͪ͛̃̄͛ṣ̷̵̞̦ͤ̅̉̋ͪ͑͛ͥ͜a̷̘͖̮͔͎͛̇̏̒͆̆͘n͇͔̤̼͙̩͖̭ͤ͋̉͌͟eͥ͒͆ͧͨ̽͞҉̹͍̳̻͢](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Use an [HTML parser](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php) instead. – Madara's Ghost Jul 21 '12 at 15:09