Home > OS >  regex to parse string from a URL
regex to parse string from a URL

Time:08-29

given the following string

https://instagram.com/USERNAME?askjda
https://www.instagram.com/USERNAME
www.instagram.com/USERNAME
www.instagram.com/USERNAME?kajsdas

how do i extract the USERNAME as string using a regex ?

CodePudding user response:

The following regex pattern should work: instagram\.com\/([^\/\r\n?] ) . See https://regex101.com/r/all2mT/1 for verification.

Example PHP code

$re = '/instagram\.com\/([^\/\r\n?] )/m';
$str = 'https://instagram.com/USERNAME?askjda';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

// Output
/*
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(22) "instagram.com/USERNAME"
    [1]=>
    string(8) "USERNAME"
  }
}
*/

By the way, you might want to include what you have tried before posting your question in the future. That is why you are getting downvoted. Also, this question does not necessarily have anything to do with PHP.

CodePudding user response:

I would do it like this. This is the easiest way

<?php
$url = 'https://instagram.com/USERNAME?askjda';

echo parse_url($url)['query'];

?>

but if you want a regex then do something like this

<?php

preg_match('/USERNAME?([^&]*)/', 'https://instagram.com/USERNAME?askjda', $matches, PREG_OFFSET_CAPTURE);
$remove = str_replace('?', '', $matches[1][0]);

echo $remove;
?>

CodePudding user response:

For the given text,

https://instagram.com/USERNAME?askjda
https://www.instagram.com/USERNAME
www.instagram.com/USERNAME
www.instagram.com/USERNAME?kajsdas

if you want to select text after USERNAME?, then use this regular expression. The first capturing group is what you need [show below]

/(?:https:\/\/|http:\/\/)?(?:www\.)?(?:\w \.\w{3}\/USERNAME\?)(\w )/g

If the USERNAME you're putting there is the placeholder for the actual username, then you might want to use this,

/(?:https:\/\/|http:\/\/)?(?:www\.)?(?:\w \.\w{3}\/)(\w )/g
  • Related