Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex to extract values from a string.(PHP)

Tags:

regex

php

cakephp

I have a string 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.

like image 829
Natasha Gomes Avatar asked Dec 22 '22 00:12

Natasha Gomes


1 Answers

It's hard to give the best answer without more information. You could try this regular expression:

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

Example code:

$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 string looks like part of a URL. If that is the case you might want to use parse_str instead. This will correctly handle a number of special cases that the regular expression won't handle correctly.

$arr = array();
parse_str(trim($s, '\"'), $arr);
print_r($arr['uid']);
like image 114
Mark Byers Avatar answered Dec 24 '22 13:12

Mark Byers