5

I need to add href=" before an http:// if this http:// doesn't follow href=" or src="

Following code partly works. Partly means it considers <a href=" only but not src="

$str= preg_replace( 
    "/(?<!a href=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", 
    "<a href=\"\\0\"> target=\"blank\">\\0</a>", 
    $str
);

Thank you guys in advance for your reply.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
Dustin Sun
  • 5,292
  • 9
  • 49
  • 87
  • 2
    See http://stackoverflow.com/questions/4003031/regex-replacing-text-url-but-exclude-image-url – Gumbo Oct 27 '10 at 20:03
  • See http://stackoverflow.com/search?q=regex+link – Gordon Oct 27 '10 at 20:48
  • 1
    You also do not want to replace the URL if it is part of an anchor element, e.g. `http://example.com` – Gordon Oct 27 '10 at 21:13
  • Or a `link`, or a `meta`, or part of a `script`, etc., etc., etc., rant, rant, rant, conclusion: use a parser. – Wrikken Oct 27 '10 at 23:04
  • Thank you Gordon. These are good thoughts. I will do it when my boss finds he needs it (to let my boss know he needs a programmer....) – Dustin Sun Oct 29 '10 at 16:11
  • possible duplicate of [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege) – Brad Mace Jul 09 '11 at 20:58
  • 1
    possible duplicate of [RegEx match open tags except XHTML self-contained tags](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – Paŭlo Ebermann Sep 15 '11 at 14:12

1 Answers1

7
$str= preg_replace( 
    "/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", 
    "<a href=\"\\0\" target=\"blank\">\\0</a>", 
    $str
);
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 1
    Would be lovely if this included any sort of description / comments. Code-only answers are hard enough, but RegEx is a whole 'nother monster! – random_user_name Jul 09 '18 at 20:54