Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instagram username from URL - ignore periods with regex

Tags:

regex

php

I've been able to retrieve the Username from an instagram profile URL with regex, however it stops once it reaches a full-stop

.

Full URL: https://www.instagram.com/username.test.uk/

The output from my regex: https://www.instagram.com/username

My regex and output:

// Regex for verifying an instagram URL
$regex = '/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im';

// Verify valid Instagram URL
if ( preg_match( $regex, $instagram_url, $matches ) ) {

    $instagram_username = $matches[1];

    var_dump($instagram_username);

The var dump produces: username

Any obvious changes needed to my regex to exclude . in the username section?

like image 233
wharfdale Avatar asked Aug 08 '18 10:08

wharfdale


1 Answers

So it stops because your match for the username doesn't include the ..

/(?:(?:http|https):\/\/)?(?:www.)?(?:instagram.com|instagr.am)\/([A-Za-z0-9-_]+)/im

This should probably include \. within ([A-Za-z0-9-_]+). You also should escape the . elsewhere in your regex so it matches only the . character instead of anything.

/(?:(?:http|https):\/\/)?(?:www\.)?(?:instagram\.com|instagr\.am)\/([A-Za-z0-9-_\.]+)/im

This will capture all alpha-numerics, underscores and dots.

like image 64
Matthew Usurp Avatar answered Nov 13 '22 03:11

Matthew Usurp