?
Solved

Use regex to get anchor text from html page

Posted on 2005-05-08
8
Medium Priority
?
612 Views
Last Modified: 2008-01-16
Given the contents of backlink as $data and the domain as $link, I want to get the anchor text that is being used to link to the domain.

ie: <a href="http://www.my_domain.com/my_folder/" target="_blank">This is the anchor text</a>

The problem is there are so many variations and possible tags associated with the a tag in html that it becomes very difficult to only filter out the coorisponding anchor text of a certain link in all cases.

Here is what I got so far:

function get_anchor($data,$link)
{
  $pattern = "/<a.*?href\s*=\s*[\"']?([^'\"> ]*?)[\"'> ]\s*.*?".">(.*?)<\/a\s*?".">/si";
  preg_match_all($pattern,$data,$matches,PREG_SET_ORDER);
  foreach($matches as $match) if(preg_match("/http:\/\/(www\.)?$link/i",$match[1])) { $anchor=$match[2]; break; }

  if(strpos($anchor,"src="))
  {
    preg_match("/alt=\"([\s\w]*)\"/i",$anchor,$alt);
    $anchor="(img) ".$alt[1];
  }
 
  if(empty($anchor)) $anchor="UNKNOWN";
  return htmlspecialchars($anchor);
}


My function seems to work for about 70-80% of the tests, but I'm looking for a 100% solution. Any ideas?
0
Comment
Question by:itcdr
8 Comments
 
LVL 10

Expert Comment

by:mensuck
ID: 13956172
You will never be able to do it 100% using a single regex, there is far to many patterns that fall in to the category you are trying to match. One thing you should not do is allow for stuff that is not valid, doing that will only make it harder to validate what is valid! For this I would use a loop, and jump from one tag to the next tag only working on tags that follow the pattern I pass to the function, then I would only do that if I was matching the same pattern more than once. While preg_match_all will be faster creating the array of matches it will end up being slower because you will need to test things that don't even 100% match characteristic that should tell you to perform the check in the first place!

From looking at your function, I see your trying to match a URL and if it's found return what is in the anchor. I think a str?() type function would be faster for doing what your function does because you are looking for only (1) match, the first one only!

Suzanne
0
 
LVL 1

Author Comment

by:itcdr
ID: 13956212
Can you give me a code example of what you think would be the best solution?
0
 
LVL 17

Expert Comment

by:davebytes
ID: 13957007
I have my own code, but it's targeting specific style href links.  But I'll try to give you some direction from standard programming practice.

Take the cases you AREN'T currently handling.  Are there commonalities between them you can break down and encode into the regex?  A good starter example might be the href= isn't the FIRST thing in the link tag.  Another might be case-sensitivity issues.

Obviously, you also start hitting things like false-positives in some cases -- but I'm kinda assuming you'd rather be over-inclusive.  I look at the 'logic' of a regex myself, as I always forget the particulars of the regex language (or switching between regex implementors...), and it's the logic you want to get right.

starts with "<a"
continues with required and optional whitespace or properties
then has "href=" (and the URL string inside quotes) property
continues with additional optional whitespace and properties
closes the tag with ">" -- note that you can use non-'>' as the match term for 'inside' the opening tag...
body of the link.  this is tricky as it could have most anything as the body.  However, in theory, you know it all ends with "</a>", so that's your terminating clause.

There are certainly instances where you might want to cover possible whitespace as well.

I'd also agree with Suzanne, there are other ways to skin this cat, with or without regex.  match on <a ... </a>, and from the inside of the match you find the first > not inside quotes, and the rest is the body of the tag.

And at that point, you could implement a search algo that looks for <a, then >, then </a>, and process it yourself.  However, even the dumb regex match on <a ... </a> I just noted would be MUCH faster than by-hand processing, due to PHP speed issues.

Hope that helps you think through it further.  Myself, I'd need to see the cases that weren't working in order to help formulate something 'better' than the above suggestions, or would start from scratch with the logic above.

-d
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 3

Expert Comment

by:designbai
ID: 13957616
hi,

Could you post your data.

thanks.
0
 
LVL 9

Accepted Solution

by:
_GeG_ earned 2000 total points
ID: 13966292
maybe try this:
preg_match("#<a[^>]*href\s*=\s*(?:'|\")?http://(?:www.){$link}[^>]*>(.*?)<\s*/\s*a\s*>#is", $data, $regs);
$anchor= $regs[1];
0
 
LVL 1

Author Comment

by:itcdr
ID: 13972501
_GeG_, It looks like you got it. Let me do some more testing first just to make sure.
0
 
LVL 1

Author Comment

by:itcdr
ID: 13974233
After a lot of testing I have found 1 major flaw, which is when there is no www
ie: <a href="http://my_domain.com">This is the anchor text</a>

Why? I thought the (?:www.) means the www is optional. How do I fix this?
0
 
LVL 1

Author Comment

by:itcdr
ID: 13974427
Now I understand. All that was missed _GeG_ example was a ? after (?:www.).

Here is the complete function:

function get_anchor($data,$link)
{
  $pattern="#<a[^>]*href\s*=\s*(?:'|\")?http://(?:www\.)?{$link}[^>]*>(.*?)</a\s*>#si";
  preg_match($pattern,$data,$match);
  $anchor=$match[1];
 
  if(strpos($anchor,"src="))
  {
    preg_match("/alt=\"([\s\w]*)\"/i",$anchor,$alt);
      return "(img) ".$alt[1];
  }
 
  if(empty($anchor)) return "UNKNOWN";
  return htmlspecialchars($anchor);
}
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month16 days, 12 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question