Reputation: 5387
I have a regular expression that finds urls in text and replaces them with links
preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href="\0" target="_blank" rel="nofollow">\0</a>', $text );
The problem is, when someone types text that contains "i.e" it converts it also to a link, which should not happen. How do I limit this regular expression to replace strings longer than 3 characters?
I tried putting {3,}
, but it's not working.
preg_replace( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)
([-A-Z0-9+&#/%=~_|$?!:,.]{3,})*[A-Z0-9+&#/%=~_|$]@i', '
<a href="\0" target="_blank" rel="nofollow">\0</a>', $text );
Upvotes: 1
Views: 107
Reputation: 3713
you can use preg_replace_callback
to check if the text captured has at least 5
or 6
chars :
preg_replace_callback( '@(?<![.*">])\b(?:(?:https?|ftp|file)://|[a-z]\.)([-A-Z0-9+&#/%=~_|$?!:,.]{3,})*[A-Z0-9+&#/%=~_|$]@i', function($matches){
if(strlen($matches[0])>5){
return '<a href="'.$matches[0].'" target="_blank" rel="nofollow">'.$matches[0].'</a>';
}else{
return $matches[0];
}
}, $text );
Upvotes: 2