3

Is this even possible...

Say I have some text with a link with a class of 'click':

<p>I am some text, i am some text, i am some text, i am some text
<a class="click" href="http://www.google.com">I am a link</a>
i am some text, i am some text, i am some text, i am some text</p>

Using PHP, get the link with class name, 'click', then get the href value?

Keith Donegan
  • 26,213
  • 34
  • 94
  • 129
  • All you need is here: http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662 phpQuery should do what you need very easily – Pekka Dec 15 '10 at 00:30

2 Answers2

8

There are a few ways to do this, the quickest is to use XPath:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$nodeList = $xpath->query('//a[@class="click"]');
foreach ($nodeList as $node) {
    $href = $node->getAttribute('href');
    $text = $node->textContent;
}
netcoder
  • 66,435
  • 19
  • 125
  • 142
3

You actually don't need to complicate your life at all:

$string='that html code with links';
// while matches found
while(preg_match('/<a class="click" href="([^"]*)">/', $string, $matches)){
    // print captured group that's actually the url your searching for
    echo $matches[1];
}
s3v3n
  • 8,203
  • 5
  • 42
  • 56
  • 1
    I think you have yet to discover the [famous bobince answer about parsing HTML with regular expressions](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). You'll never want to do it again after that... :) – netcoder Dec 15 '10 at 00:55
  • 1
    This is a simple example, why to complicate all the things in this way? – s3v3n Dec 15 '10 at 01:03