Validate Facebook URLs & Twitter Usernames with PHP Regular Expression



I was looking for a way to validate Facebook and Twitter user input and found relatively little information on it so I wrote these 2 little functions:

Facebook URL Regex

protected function valid_facebook_url($field){
    if(!preg_match('/^(http\:\/\/|https\:\/\/)?(?:www\.)?facebook\.com\/(?:(?:\w\.)*#!\/)?(?:pages\/)?(?:[\w\-\.]*\/)*([\w\-\.]*)/', $field)){
        return false;
    }
    return true;
}

Twitter Username Regex

protected function valid_twitter_username($field){
    if(!preg_match('/^(\@)?[A-Za-z0-9_]+$/', $field)){
        return false;
    }
    return true;
}

Hope this helps, I’m not 100% sure on the regex stuff so if you have any better methods let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *