-1

I want to get value from a href.

Here is the HTML I am working with:

<div class="streeet"> 
  <b>Name:</b>wwww<br />
  <b>Post Code:</b>97
  <b>City:</b>
  <a href="/bar-fan-pers.html" title="abcd">VALUE</a> 
  <br />
</div>

I am trying to use preg_match_all:

preg_match_all('/<div\s*class=\"walldetsleft\">[^>]*<a\s*href=\"[^>]*\"\s[^\>]*>(.*?)<\/a>/', $url, $val);

It does not work - the output is just an empty array. How can I write a regex to do this?

Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
KunKun
  • 67
  • 1
  • 9

2 Answers2

0

This isn't the regex you asked for but it's what I recommend:

$html = '
<div class="streeet"> 
  <b>Name:</b>wwww<br />
  <b>Post Code:</b>97
  <b>City:</b>
  <a href="/bar-fan-pers.html" title="abcd">VALUE</a> 
  <br />
</div>';

// handle parsing errors yourself
libxml_use_internal_errors(true);
// instantiate new `DOMDocument` object
$dom = new DOMDocument();
// load $html into `DOMDocument`
$dom->loadHTML($html);
// get all anchor elements
$elements = $dom->getElementsByTagName('a');
// iterate over anchors
foreach($elements as $element) {
    // get href attribute
    $href = $element->getAttribute('href');
    echo $href . PHP_EOL;
}
0

You can do something like the following:

$doc = new DOMDocument;
 $source = '<div class="streeet"> 
  <b>Name:</b>wwww<br />
  <b>Post Code:</b>97
  <b>City:</b>
  <a href="/bar-fan-pers.html" title="abcd">VALUE</a> 
  <br />
</div>';
 $doc->loadHTML($source);     
 $out = $doc->getElementsByTagName('a')->item(0)->attributes->getNamedItem('href')->nodeValue;
echo $out;
SaidbakR
  • 13,303
  • 20
  • 101
  • 195