【问题标题】:How to get content within a A HREF tag using wildcard (PHP)如何使用通配符 (PHP) 在 A HREF 标记中获取内容
【发布时间】:2020-06-16 04:16:35
【问题描述】:

我试图在 PHP 中获取一系列 A HREF 标记的内容,例如:

<a href="/user/200890"></a>
<a href="/user/200891"></a>
<a href="/user/200892"></a>

我正在使用这个,但不知道如何使用通配符获取所有标签 - 我试过这个,但没用:

$anchorTags = $xPath->evaluate("//a[@href*=\"/user\"]");

谢谢!

【问题讨论】:

    标签: php xpath wildcard


    【解决方案1】:

    您可以在 XPath 查询中使用 start-with 选择器

    $strhtml='
        <a href="/user/200890"></a>
        <a href="/user/200891"></a>
        <a href="/user/200892"></a>     
    ';
    
    
    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->strictErrorChecking=false;
    $dom->loadHTML( $strhtml );
    $errors=libxml_get_errors();
    libxml_clear_errors();
    
    
    $xp=new DOMXPath( $dom );
    $pttn='//a[ starts-with( @href, "/user/" ) ]';
    
    $col=$xp->query( $pttn );
    if( $col && $col->length > 0 ){
        foreach( $col as $node )echo $node->getAttribute('href') . '<br>';
    }
    

    按预期输出:

    /user/200890
    /user/200891
    /user/200892
    

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2011-10-04
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多