I have the following code :
$html = get_data($url);
I want to extract a session ID from this code, which has the following form :
PHPSESSID=aaabbb123456789;
I'd like to store the session id (only the ID) in a var. I use this regexp :
preg_match('#PHPSESSID=(.+?);#is', $html, $result);
I almost get what I want, but the $result tab contains two strings. Here is the var_dump()
:
array(2) { [0]=> string(37) "PHPSESSID=aaabbb123456789;" [1]=> string(26) "aaabbb123456789" }
I would like preg_match()
to return only the ID, as in $result[1]
. What should I change in the regexp ?
Thanks
The result list of regex matches often has the first result being the entire string. PHP's preg_match()
guarantees this as well:
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.
So you can safely just extract the value as $result[1]
without worrying that it might change and cause a warning.