Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regular expression to replace link url

Tags:

regex

php

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.

like image 528
Dustin Sun Avatar asked Oct 27 '10 19:10

Dustin Sun


1 Answers

$str= preg_replace( 
    "/(?<!a href=\")(?<!src=\")((http|ftp)+(s)?:\/\/[^<>\s]+)/i", 
    "<a href=\"\\0\" target=\"blank\">\\0</a>", 
    $str
);
like image 181
chaos Avatar answered Oct 21 '22 00:10

chaos