Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP extract link from <a> tag [duplicate]

Possible Duplicate:
PHP String Manipulation: Extract hrefs

I am using php and have string with content =

<a href="www.something.com">Click here</a>

I need to get rid of everything except "www.something.com" I assume this can be done with regular expressions. Any help is appreciated! Thank you

like image 306
5et Avatar asked Jun 15 '11 23:06

5et


2 Answers

This is very easy to do using SimpleXML:

$a = new SimpleXMLElement('<a href="www.something.com">Click here</a>');
echo $a['href']; // will echo www.something.com
like image 195
mfonda Avatar answered Sep 22 '22 13:09

mfonda


Give this a whirl:

$link = '<a href="www.something.com">Click here</a>';
preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $link, $result);

if (!empty($result)) {
    # Found a link.
    echo $result['href'][0];
}

Result: www.something.com

Updated: Now requires the quoting style to match, addressing the comment below.

like image 44
Tails Avatar answered Sep 25 '22 13:09

Tails