Jump to content

preg_match links in div...


ShibSta

Recommended Posts

I have the HTML similar to the following:

<a href="#noMatch">Link</a>
<div class="title">
    <a href="#1" class="noBorder">Link</a>, 
    <a href="#2" class="">Link2</a>, 
    <a class="" href="#3">Link3</a>, 
</div>

 

I am trying to get the href and innerHTML of each link. The ultimate goal is to have an array like so:

$arr = array( 
    array( "href" => "#1", "text" => "Link"  ), 
    array( "href" => "#2", "text" => "Link2"  ), 
    array( "href" => "#3", "text" => "Link3"  ) 
);

 

I've managed to match the 1st link in the div but have since then changed the code and have not been able to reproduce it. Regular Expressions are certainly my weakest point, I always get stuck on them. :(

 

Thanks, in advance.

Link to comment
https://forums.phpfreaks.com/topic/176782-preg_match-links-in-div/
Share on other sites

How consistent will the anchor links be? Will they always be 'best form' in as much as they will always use double quotes for the href? If so then this will extract the links, but it won't locate specifcally within the <div> not entirely sure how to do that and haven't got time atm to experiment. You will have to then loop through $out to create your $arr format.

 

$input = preg_match
preg_match_all('~<a href="([^"]*).*?>(.*?)</a>~is', $input, $out);

 

Edit: You could probably fetch the contents of the <div> using something like this to find the <input> for above, but I'm sure it can probably all be done with one regex.

 

preg_match('~<div class="title">(.*?)</div>~is', $input, $out);

When it comes to html, I would stick to dom / domxpath personally..

 

Example:

$html = <<<EOF
<a href="#noMatch">Link</a>
<div class="title">
    <a href="#1" class="noBorder">Link</a>,
    <a href="#2" class="">Link2</a>,
    <a class="" href="#3">Link3</a>,
</div>
EOF;

$arr = array();
$dom = new DOMDocument;
@$dom->loadHTML($html); // change loadHTML to loadHTMLFile and put a legit url within the parenthesis if you want to apply this to a site
$xpath = new DOMXPath($dom);
$aTag = $xpath->query('//div[@class="title"]/a[@href]'); // find anchor tags (which contain the attribute href), of which are children of div tags that contain the class 'title'

foreach ($aTag as $val) {
    $arr[] = array("href"=>$val->getAttribute('href'), "text"=>$val->nodeValue);
}

echo '<pre>'.print_r($arr, true);

 

Output:

Array
(
    [0] => Array
        (
            [href] => #1
            [text] => Link
        )

    [1] => Array
        (
            [href] => #2
            [text] => Link2
        )

    [2] => Array
        (
            [href] => #3
            [text] => Link3
        )

)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.