1

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?

3

2 Answers 2

0

Check out Regex to find the HTML tag

2
  • 2
    The <center> can not hold! stackoverflow.com/questions/1732348/…
    – user50049
    Mar 16, 2010 at 17:10
  • 1
    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
    Mar 16, 2010 at 18:21
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.