Reputation: 7693
I'm using regex with PHP's preg_replace when processing user input to make hyperlinks come to life using this piece of code:
preg_replace(
'!(((f|ht)tp://)[-a-zA-Zа-яА-Я()0-9@:%_+.~#?&;//=]+)!i',
'<a class="external" href="$1">$1</a>',
$text
);
What I need to do, however, is to ignore all links encased in {{ }}
, so for example, this input should be processed by regex:
http://www.example.com/
This input should be ignored:
{{http://www.example.com/}}
How can I change my regex pattern to work as expected?
Upvotes: 0
Views: 90
Reputation: 121720
Surround your regex with a negative lookbehind ((?<!...)
) and a negative lookahead ((?!...)
):
'/(?<!\{\{)(((f|ht)tp:\/\/)[-a-zа-я()0-9@:%_+.~#?&;\/=]+)(?!\}\})/i'
Alternatively, just go through the text word by word, and try and see if a word is a valid URL using a URL parsing library (you cannot have a space in a URL); and replace only in this case.
Upvotes: 3