简体   繁体   中英

How to get content within a A HREF tag using wildcard (PHP)

Im trying to get content of a series of A HREF tags in PHP, eg:

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

I'm using this, but don't know how to get all tags using wildcard - I tried this, bu didn't work:

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

Thanks!

You can use the start-with selector in your XPath query

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

This outputs, as expected:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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