【问题标题】:Regex - get href value from a tag正则表达式 - 从标签中获取 href 值
【发布时间】:2016-12-04 07:45:33
【问题描述】:

我想从 href 中获得价值。

这是我正在使用的 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>

我正在尝试使用preg_match_all:

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

它不起作用 - 输出只是一个空数组。我该如何编写一个正则表达式来做到这一点?

【问题讨论】:

标签: php html regex


【解决方案1】:

这不是您要求的正则表达式,但这是我推荐的:

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

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 2016-05-22
      • 2014-05-18
      相关资源
      最近更新 更多