brewpixels
brewpixels

Reputation: 311

Regex to check for facebook url AND be only alphanumeric.

I made this script that requires that the user enter a facebook url. That part works well but a user can still add special characters in the url variable, and I'm trying to prevent this.

I want the regex to only allow alphanumeric characters, dashes, and underscores. And not to allow spaces.

I tried adding [a-zA-Z0-9_] to my regex but it doesn't work.

<?php
$facebook_url = "http://www.facebook.com/user";

if(!preg_match('^facebook\.com\S*[a-zA-Z0-9_]*^', $facebook_url)){
//if(!preg_match('^http://(?:.*\.)?facebook\.com\S*[a-zA-Z0-9_]*^', $facebook_url)){

    echo "ummm, this is not a facebook url";

} else {

    echo "this is a facebook url";

}
?>

<br />

<a href="<?php echo $facebook_url?>" target="_blank">My Facebook</a>

Upvotes: 0

Views: 3557

Answers (2)

Bookin
Bookin

Reputation: 282

Of couse you should remove '^' character. (This sign marks the beginning of the line)

preg_match('/(https?:\/\/)?([\w\.]*)facebook\.com\/([a-zA-Z0-9_]*)$/', $facebook_url)

Upvotes: 3

Sergey Mazur
Sergey Mazur

Reputation: 41

Please remove '^' characters from the beginning and the end. Use this:

'facebook\.com\/[a-zA-Z0-9_]*$'

P.S. Underscore ('_') is also allowed in url. Without underscore:

'facebook\.com\/[a-zA-Z0-9]*$'

Upvotes: 0

Related Questions