Php preg_match help get facebook username / id from url

I am trying to get the username or facebook id from the facebook url and wondered if you can help me. I am sure this is just a simple regular expression function, but I tried and cannot do it myself.

Here is what I tried to get from the url.

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

or numeric identifier

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

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

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

The template is universal, so it corresponds to:

  • http and https URL.
  • URL with www prefix or without it.
  • URL with or without trailing.
  • Corresponds to Facebook's digital identifiers.
  • Complies with Facebook user policies .

Usernames may contain only alphanumeric characters (AZ, 0-9) or period (".").

+14
source

Without regex:

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

Source: https://habr.com/ru/post/1437273/


All Articles