Search code examples
special-characterspreg-match-all

Extract Two Value between special characters with Preg_Match


Hello I want to Extract the username and Password value with one preg_match_all

$url='http://xxxxxxxx.com:80/get.php?username=xxxxxx&password=xxxxxx&type=m3u_plus';

I get wiht this explode where i want but i know is more effect with preg_match_all can you show me how.?

$url_ext = parse_url($url);
$username=explode ("&",explode("=",$url_ext['query'])[1]);
$password=explode ("&",explode("=",$url_ext['query'])[2]);

I try with this code but not working

$lotes_fil='~https?://.\=(.+?)&~';
preg_match_all($lotes_fil,$url,$link_pre);

Solution

  • It is better to use parse_url and parse_str like explained here.

    But, if you really want a regex, this does the job:

    (?<=[?&])([^&=\r\n]+)=([^&=\r\n]+)

    preg_match_all('/(?<=[?&])([^&=\r\n]+)=([^&=\r\n]+)/', $url, $matches);
    

    The parameter name is in group 1, the value in group 2

    Demo & explanation