How to use a regular expression to extract values ​​from a string. (Php)

I have a line like this

\"access_token=103782364732640461|2.ZmElnDTiZlkgXbT8e34Jrw__.3600.1281891600-10000186237005083013|yD4raWxWkDe3DLPJZIRox4H6Q_k.&expires=1281891600&secret=YF5OL_fUXItLJ3dKQpQf5w__&session_key=2.ZmElnDTiZlkgXbT8e34Jrw__.3600.1281891600-10000186237005083013&sig=a2b3fdac30d53a7cca34de924dff8440&uid=10000186237005083013\"

I want to extract the UID.

+3
source share
1 answer

It is difficult to give a better answer without additional information. You can try this regex:

'/&uid=([0-9]+)/'

Code example:

$s = '\"access_token=103782364732640461|2.ZmElnDTiZlkgXbT8e34Jrw__.3600.1281891600-10000186237005083013|yD4raWxWkDe3DLPJZIRox4H6Q_k.&expires=1281891600&secret=YF5OL_fUXItLJ3dKQpQf5w__&session_key=2.ZmElnDTiZlkgXbT8e34Jrw__.3600.1281891600-10000186237005083013&sig=a2b3fdac30d53a7cca34de924dff8440&uid=10000186237005083013\"';
$matches = array();
$s = preg_match('/&uid=([0-9]+)/', $s, $matches);
print_r($matches[1]);

Result:

10000186237005083013

But I notice that your input line looks like part of the url. If so, you can use parse_str . This will correctly handle a number of special cases where the regular expression will not be processed correctly.

$arr = array();
parse_str(trim($s, '\"'), $arr);
print_r($arr['uid']);
+10
source

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


All Articles