Natasha Gomes
Natasha Gomes

Reputation: 41

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

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.

Upvotes: 4

Views: 9087

Answers (1)

Mark Byers
Mark Byers

Reputation: 838696

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']);

Upvotes: 12

Related Questions