Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match help getting facebook username/id from URL

I am trying to get the facebook username or id from a facebook url and was wondering if you could help me. I'm sure it's just a simple regex function but I have tried and can't seem to do it myself.

Here's what I've been trying to get from the url.

http://www.facebook.com/myusername/

or the numerical id

http://www.facebook.com/2285652/

I would be very grateful if anyone could help me achieve this via PHP

like image 502
Frank Avatar asked Oct 01 '12 19:10

Frank


1 Answers

preg_match('#https?\://(?:www\.)?facebook\.com/(\d+|[A-Za-z0-9\.]+)/?#',$str,$matches);

The pattern is versatile so it matches:

  1. http and https URL's.
  2. URL's with or without the www prefix.
  3. URL's with or without the trailing /.
  4. Matches Facebook numerical ID's.
  5. Matches Facebook's rules for usernames.

Usernames can only contain alphanumeric characters (A-Z, 0-9) or a period (".").

like image 119
jimp Avatar answered Sep 22 '22 19:09

jimp