PHP Regular Expression To Match Any URL Except Those From Example.com

Provide an example for the pseudo-regex: Match every url except those from example.com and example2.com according to the PHP regexp syntax.

Here is what I have so far, but it doesn't work:

$patternToMatch = "@https?://[^(example.com|example2.com)]\"*@i";

Answers


The problem here is that within a class definition ([]) special characters such as ( and | lose their meaning.

A better solution is to match on example.com or example2.com and then proceed only for negative tests.


Don't use regular expressions for things you don't need to.

$parts = parse_url($url);
if ($parts && $parts['host'] != 'example.com' && $parts['host'] != 'example2.com') {
    // the URL seems OK
}

No, everything between square brackets will match just one character. For example the regex:

[^example]

will match any single character other than e, x, a, m, p, l and e.

Try negative lookahead:

@https?://(www\.)?(?!example2?.com)@i

You almost had the answer. This will do the matching that you want.

$patternToMatch = "@https?://(example.com|example2.com)@i";

Need Your Help

pHp Form Send - Save Data to Table, send activation email?

php forms email table activation

I'm trying to crete a form that will create a user in my database, so they can have a profile page. I'd also like the form to send an email to confirm activation. Where is my form disconnecting? As...

How to customize validates_length_of message to include attribute length?

ruby-on-rails ruby-on-rails-3

I want to customize the error message on a validates_length_of to include the length of the attribute being checked. I know we can do "%{value}" or "%{attribute}" within the message to get those v...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.