Jump to content

get rid of excess code


dreamwest

Recommended Posts

Im trying to break apart a group of hyperlinks so im just left with the actual url:

 

html here<a class='link' href='http://www.site.com/?q=6J4W2G4fASI'>html here

html here<a class='link' href='http://www.site.com/?q=637yfuhqelhe'>html here

html here<a class='link' href='http://www.site.com/?q=hilghye8oyhi'>html here

etc...

 

so the result would be :

 

http://www.site.com/?q=6J4W2G4fASI

http://www.site.com/?q=637yfuhqelhe

http://www.site.com/?q=hilghye8oyhi

 

Link to comment
Share on other sites

You can grab the URLs with regex:

 

<?php
$str = "html here<a class='link' href='http://www.site.com/?q=6J4W2G4fASI'>html here
html here<a class='link' href='http://www.site.com/?q=637yfuhqelhe'>html here
html here<a class='link' href='http://www.site.com/?q=hilghye8oyhi'>html here";
preg_match_all('~<a\b[^>]+href\s?=\s?[\'"](.*?)[\'"]~is', $str, $matches);
echo '<pre>' . print_r($matches[1], true) . '</pre>';
?>

 

Note that $matches[1] will be an array of the URLs.

 

Or alternatively use PHP DOM:

 

<?php
$urls = array();
$str = "html here<a class='link' href='http://www.site.com/?q=6J4W2G4fASI'>html here
html here<a class='link' href='http://www.site.com/?q=637yfuhqelhe'>html here
html here<a class='link' href='http://www.site.com/?q=hilghye8oyhi'>html here";
$dom = new DOMDocument();
$dom->loadHTML($str);
$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
$urls[] = $tag->getAttribute('href');
}
echo '<pre>' . print_r($urls, true) . '</pre>';
?>

Link to comment
Share on other sites

You can grab the URLs with regex:

 

<?php
$str = "html here<a class='link' href='http://www.site.com/?q=6J4W2G4fASI'>html here
html here<a class='link' href='http://www.site.com/?q=637yfuhqelhe'>html here
html here<a class='link' href='http://www.site.com/?q=hilghye8oyhi'>html here";
preg_match_all('~<a\b[^>]+href\s?=\s?[\'"](.*?)[\'"]~is', $str, $matches);
echo '<pre>' . print_r($matches[1], true) . '</pre>';
?>

 

Note that $matches[1] will be an array of the URLs.

 

Sweet thanks!

 

I knew preg_match_all would do it but couldnt get my head around the regex

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.