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
https://forums.phpfreaks.com/topic/173460-get-rid-of-excess-code/
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>';
?>

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

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.