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:
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
Post a Comment