如何找到字符串中最接近字符的链接/ url? (PHP)

I'm searching for a link or url in an html email closest to a search term that I've found in an email.

Right now I'm using stripos('Haystack','SearchTerm') to locate the phrase in the string.

I also either want to find if this searchterm is inside a tag, and if so get the href="THIS VALUE". If it's not inside <a></a>, then I'd like to find the closest href="" reference and get that URL.

I just don't know how you find relative nearness of substrings inside a string.

Try to look on regular expressions ( preg_replace or preg_match in your case ) - i cannot say more now , because i don't know what "relatice nearness" ?

What you could do, is split the string at the substring position using explode() and then get the first occurence of an URL in the resulting substring:

$parts = explode("SEPARATOR", $data);
if (count($parts) > 1) {
  $haystack = $parts[1];
  // Use regex here to extract first URL in newly created $haystack
}