除某些条件外,正则表达式等于条件

I have written the following Regex in PHP for use within preg_replace().

/\b\S*(.com|.net|.us|.biz|.org|.info|.xxx|.mx|.ca|.fr|.in|.cn|.hk|.ng|.pr|.ph|.tv|.ru|.ly|.de|.my|.ir)\S*\b/i

This regex removes all URLs from a string pretty effectively this far (though I am sure I can write a better one). I need to be able to add an exclusion though from a specific domain. So the pseudo code will look like this:

IF string contains: .com or .net or. biz etc... and does not contain: foo.com THEN execute condition.

Any idea on how to do this?

Just add a negative lookahead assertion:

/(?<=\s|^)(?!\S*foo\.com)\S*\.(com|net|us|biz|org|info|xxx|mx|ca|fr|in|cn|hk|ng|pr|ph|tv|ru|ly|de|my|ir)\S*\b/im

Also, remember that you need to escape the dot - and that you can move it outside the alternation since each of the alternatives starts with a dot.

Use preg_replace_callback instead. Let your callback decide whether to replace.

It can give more flexibility if the requirements become too complicated for a simple regex.