如何使用正则表达式从字符串中提取值。(PHP)

时间:2022-09-13 11:06:12

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.

我想提取UID。

1 个解决方案

#1


11  

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.

但我注意到您的输入字符串看起来像URL的一部分。如果是这种情况,您可能希望使用parse_str。这将正确处理正则表达式无法正确处理的许多特殊情况。

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

#1


11  

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.

但我注意到您的输入字符串看起来像URL的一部分。如果是这种情况,您可能希望使用parse_str。这将正确处理正则表达式无法正确处理的许多特殊情况。

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