简体   繁体   English

正则表达式 - 从标签中获取 href 值

[英]Regex - get href value from a tag

I want to get value from a href.我想从 href 中获取价值。

Here is the HTML I am working with:这是我正在使用的 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>

I am trying to use preg_match_all :我正在尝试使用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?我怎样才能写一个正则表达式来做到这一点?

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;
}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM