PHP 正则表达式 header (session id)
PHP Regexp header (session id)
我有以下代码:
$html = get_data($url);
我想从这段代码中提取一个 session ID,其格式如下:
PHPSESSID=aaabbb123456789;
我想将 session id(仅 ID)存储在 var 中。我使用这个正则表达式:
preg_match('#PHPSESSID=(.+?);#is', $html, $result);
我几乎得到了我想要的,但是 $result 选项卡包含两个字符串。这是 var_dump()
:
array(2) { [0]=> string(37) "PHPSESSID=aaabbb123456789;" [1]=> string(26) "aaabbb123456789" }
我想 preg_match()
到 return 只有 ID,如 $result[1]
。我应该在正则表达式中更改什么?
谢谢
正则表达式匹配的结果列表通常第一个结果是整个字符串。 PHP 的 preg_match()
也保证了这一点:
If matches is provided, then it is filled with the results of search. $matches[0]
will contain the text that matched the full pattern, $matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
因此您可以安全地将值提取为 $result[1]
,而不必担心它可能会更改并引起警告。
这并不能完全回答您的问题,但是当涉及到字符串处理和解析时,我通常宁愿在不需要时不使用正则表达式
str_replace("PHPSESSID=", "", str_replace(";", "", $yourString));
除非你的字符串包含超过"PHPSESSID=aaabbb123456789;"
您无法更改它,这就是该命令的工作方式。
$result[0] 将始终是整个匹配的正则表达式,而之后的每个索引将对应一个组。
您可以通过不使用组来消除后续索引,如下所示:
preg_match('#(?<=PHPSESSID=)[^;]+#i', $html, $result);
现在会话 ID 将始终在 $result[0]
中
array(1) { [0]=> string(15) "aaabbb123456789" }
我有以下代码:
$html = get_data($url);
我想从这段代码中提取一个 session ID,其格式如下:
PHPSESSID=aaabbb123456789;
我想将 session id(仅 ID)存储在 var 中。我使用这个正则表达式:
preg_match('#PHPSESSID=(.+?);#is', $html, $result);
我几乎得到了我想要的,但是 $result 选项卡包含两个字符串。这是 var_dump()
:
array(2) { [0]=> string(37) "PHPSESSID=aaabbb123456789;" [1]=> string(26) "aaabbb123456789" }
我想 preg_match()
到 return 只有 ID,如 $result[1]
。我应该在正则表达式中更改什么?
谢谢
正则表达式匹配的结果列表通常第一个结果是整个字符串。 PHP 的 preg_match()
也保证了这一点:
If matches is provided, then it is filled with the results of search.
$matches[0]
will contain the text that matched the full pattern,$matches[1]
will have the text that matched the first captured parenthesized subpattern, and so on.
因此您可以安全地将值提取为 $result[1]
,而不必担心它可能会更改并引起警告。
这并不能完全回答您的问题,但是当涉及到字符串处理和解析时,我通常宁愿在不需要时不使用正则表达式
str_replace("PHPSESSID=", "", str_replace(";", "", $yourString));
除非你的字符串包含超过"PHPSESSID=aaabbb123456789;"
您无法更改它,这就是该命令的工作方式。
$result[0] 将始终是整个匹配的正则表达式,而之后的每个索引将对应一个组。
您可以通过不使用组来消除后续索引,如下所示:
preg_match('#(?<=PHPSESSID=)[^;]+#i', $html, $result);
现在会话 ID 将始终在 $result[0]
中array(1) { [0]=> string(15) "aaabbb123456789" }