Erik W
Erik W

Reputation: 807

Get URL of specific link in PHP

I have a file that contains a bunch of links:

<a href="http://site1.com">site 1</a>
<a href="http://site2.com">site 2</a>
<a href="http://site3.com">site 3</a>

I want to get the URL to a link with specific text. For example, search for "site 2" and get back "http://site2.com"

I tried this:

preg_match("/.*?[Hh][Rr][Ee][Ff]=\"(.*?)\">site 2<\/[Aa]>.*/", $contents, $match)

(I know the HREF= will be the last part of the anchor)

But it returns

http://site1.com">site 1</a><a href="http://site2.com

Is there a way to do a search backwards, or something? I know I can do preg_match_all and loop over everything, but I'm trying to avoid that.

Upvotes: 0

Views: 892

Answers (2)

AndreKR
AndreKR

Reputation: 33678

Or you can try using phpQuery.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Try this:

preg_match("(<a.*?href=[\"']([^\"']+)[\"'][^>]?>site 2</a>)i",$contents,$match);
$result = $match[1];

Hope this helps!

Upvotes: 1

Related Questions