searching a page for links and putting links into array - beginner

Discussion in 'PHP' started by angrypenguin, Sep 1, 2007.

  1. #1
    Hi all, I'm trying to search a page for links and put the links into an array. Is there a specific function for doing this, or do I have to search for '<a href="' then read the link in.

    I'm thinking of something like this:
    
    $file = fopen("links.html","r");
    while (!feof($file))
    {
    // get line from file
    // check if it's a link
    // put link into array
    }
    fclose($file);
    Code (markup):
    Does anyone have any ideas?
     
    angrypenguin, Sep 1, 2007 IP
  2. James.Blant

    James.Blant Active Member

    Messages:
    250
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    60
    #2
    you can using regex to catch links .
    search in google regex or using a thread in this section with regex help .
     
    James.Blant, Sep 1, 2007 IP
  3. ger

    ger Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Try something like this:

    function grablinks($filename)
    {
    	// grab the lines in the file
    	$lines = file($filename);
    	foreach ($lines as $line)
    	{
    		// in each line find all <a ... href="..." .../> tags and extract the actual link
    		$count = preg_match_all("/<a[^>]*href=[\"']([^\"']*)[\"'][^>]*>/", $line, $matches);
    		// if there was at least one link found in the current line
    		if ($count > 0)
    		{
    			// do something with all matched links 
    			for ($i=0; $i<count($matches[0]); $i++)
    				echo $matches[1][$i] . "<br/>";
    		}
    	}
    }
    Code (markup):
    Cheers,
    Gabi.
     
    ger, Sep 1, 2007 IP