views:

70

answers:

2

I have rather long entries being submitted to a database.

How can I create a function to see if this entry has a link within it? Can someone get me started?

Pretty much, I want the function to find any <a, <a href or any other related link instances within a string.

I'd prefer not to throw the entry into an array. Are there any other ways to accomplish this?

A: 

Check out Regex to find the HTML tag

Joel
The <center> can not hold! http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454
Tim Post
Ok, cool. That's an interesting read. I would agree that regex wouldn't be ideal for every case, but the poster asked to find any "<a" or "<a href" tags. You're telling me that regex can't do that? I beg to differ
Joel
A: 

If you want to stay away from RegEx, you could use an ugly combination of strpos and substr to find "<a " extract that, etc.

Something ugly like this (this only finds the first link, it will fail with bad code, and it doesn't find ' (which is invalid XHTML)) p.s. this is a bad idea:

function findLink($string) {
  $pos = strpos($string, "<a ");
  if ($pos === false)
    return false;

  $string = substr($string, $pos);
  $pos = strpos($string, "href");
  $string = substr($string, $pos);

  // First quote
  $pos = strpos($string, '"');
  $string = substr($string, $pos + 1);

  // Last quote
  $pos = strpos($string, '"');
  $string = substr($string, 0, $pos);

  if (trim($string) != "")
    return $string;
  return false;
}

I'm sure you could also try tokenizing the string?

$token = strtok($string, "\"'");
while ($token !== false) {
  // Look for anything with a link in it
  str_replace(array("http://", "www", "ftp://"), "", ltrim($string), $count);
  if ($count > 0)
    return $string;
  $token = strtok($string, "\"'");
}
return false;

Note: these are NOT great ways to do this.

St. John Johnson