Reputation: 65
i'm struggling to find an answer for the following... i suspect I don't really know what i'm asking for or how to ask it... let me describe:
I would like to grab some links from a page. I only want the links that have the following word as part of the URL: "advertid". Therefore and for example, the URL would be something like http://thisisanadvertis.com/questions/ask.
I've got this far
<?php
// This is our starting point. Change this to whatever URL you want.
$start = "https://example.com";
function follow_links($url) {
// Create a new instance of PHP's DOMDocument class.
$doc = new DOMDocument();
// Use file_get_contents() to download the page, pass the output of file_get_contents()
// to PHP's DOMDocument class.
@$doc->loadHTML(@file_get_contents($url));
// Create an array of all of the links we find on the page.
$linklist = $doc->getElementsByTagName("a");
// Loop through all of the links we find.
foreach ($linklist as $link) {
echo $link->getAttribute("href")."\n";
}
}
// Begin the crawling process by crawling the starting link first.
follow_links($start);
?>
This returns all URLs on the page... which is OK. So to try and get the URLs i wanted, i tried a few things including trying to amend the getattribute part:
echo $link->getAttribute("href"."*advertid*")."\n";
I've tried a few things... but can't get what i want. Can someone point me in the right direction, i'm a bit stuck.
Many thanks in advance.
Upvotes: 0
Views: 173
Reputation: 238
$links = []
foreach ($linklist as $link) {
$href = $link->getAttribute("href");
if (preg_match('/.*advertid.*/', $href)) {
array_push($links, $href);
}
}
Upvotes: 1
Reputation: 163
I would suggest you to use PHP function strpos
strpos takes at least two parameter, the first is the string you're searching in. The second parameter is what you're looking for in the first string.
strpos returns the position of the string if it's found, or false if it's not found.
So your loop would look something like :
foreach ($linklist as $link) {
if( strpos($link->getAttribute("href"), 'advertid') !== false ){
echo $link->getAttribute("href")."\n";
}
}
Upvotes: 0
Reputation: 15131
You can check if the href attribute has the info you want, with some logic, dependending on the case:
foreach ($linklist as $link) {
if(strpos($link->getAttribute("href"), 'advertid') >= 0) {
echo $link->getAttribute("href")."\n";
}
}
Upvotes: 1
Reputation: 1506
foreach ($linklist as $link) {
if (strpos($link->getAttribute("href"), 'advertid') !== false) {
echo $link->getAttribute("href")."\n";
}
}
Upvotes: 1