user3736026
user3736026

Reputation: 33

Regular expression for allowing specific URLs

Regex is very confusing especially for long urls. Here is a code that that checks an URL and stores a customized message in $msg variable. In this example, it allows all URLs except facebook. I need to make some changes.

It should allow all URLs, it should NOT allow facebook url except the ones that has videos

if(some url website link){
        $msg = 'url allowed';
    }elseif(preg_match("|^http(s)?://(www.)?facebook.([a-z]+)/(.*)?$|i", $url)){
        $msg = 'url NOT allowed';
    }else{some other url test
}

https://www.facebook.com/video.php?v=100000000000000 should be allowed. How to I write the regex for allowing only video URL of facebook and not other URLs of facebook.

I want to do this for one more fb URL too like https://www.facebook.com/username/posts/100000000000000 (should be allowed)

Thank you

Upvotes: 1

Views: 1609

Answers (1)

Amal Murali
Amal Murali

Reputation: 76656

You can use the following regex to match all facebook.com URLs that are not videos or status updates:

^http(s)?://(www\.)?facebook.([a-z]+)/(?!(?:video\.php\?v=\d+|username/posts/\d+)).*$

Explanation:

^                    # Assert position at the beginning of the line
http(s)?://          # The protocol information
(www\.)?             # Match 'www.'
facebook\.           # Match 'facebook.'
([a-z]+)             # Match the TLD
/                    # A literal forward slash '/'
(?!                  # If not followed by:
 (?:                 # Start of non-capturing group
 video\.php\?v=\d+   #   a video URL
 |                   #   OR
 username/posts/\d+  #   a status update URL
 )                   # End of non-capturing group
)                    # End of negative lookahead
.*                   # Match everything until the end if above condition true
$                    # Assert position at the end of the line

RegEx Demo

Upvotes: 2

Related Questions