php - Exclude link starts with a character from PREG_REPLACE -


this codes convert url clickable link:

$str = preg_replace('/(http[s]?:\/\/[^\s]*)/i', '<a href="$1">$1</a>', $str); 

how make not convert when url starts [ character? this:

[http://google.com

use negative lookbehind:

$str = preg_replace('/(?<!\[)(http[s]?:\/\/[^\s]*)/i', '<a href="$1">$1</a>', $str);                       ^^^^^^^ 

then, http... substring preceded [ won't matched.

you may enhance pattern as

preg_replace('/(?<!\[)https?:\/\/\s*/i', '<a href="$0">$0</a>', $str); 

that is: remove ( , ) (the capturing group) , replace backreferences $1 $0 in replacement pattern, , mind [^\s] = \s, shorter. also, [s]? = s?.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -