5
votes

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

2

2 Answers

16
votes
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 (".").

4
votes

Without regex:

$array = parse_url($url);
echo trim($array['path'], '/');