开发者

PHP: sscanf extract values from string within double quotes [duplicate]

This question already has an answer here: How to unserialize an ArrayObject (1 answer) Closed 1 year ago.

I'm trying to parse the 2 values conta开发者_运维问答ined within double quotes from a session string. The other string variables are not constant and therefore can not use any additional characters as markers. I only need the quoted values. My following sscanf function is incomplete.

$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';

sscanf($string,'%[^"]', $login_ip, $login_date);

echo $login_ip;
echo $login_date;

Thanks for your help.


That data is just PHP serialized text from serialize()

In which case you can get at the data you need with:

$sessionData = unserialize('a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
list($ip, $date) = each($sessionData);


$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';

preg_matches("/(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)/",$string,$matches);

echo $matches[1];

This should return your ip address. consult php.net


You can use regex to do that.

$string = 'a:1:{s:14:"174.29.144.241";s:8:"20110508";}';
$pattern = '/"(?P<ip>[^"]*)"[^"]*"(?P<date>[^"]*)"/';
preg_match( $pattern, $string, $matches );
echo $matches['ip'].' '.$matches['date'];

First quoted value will go to ip, second to date.


An interesting hack would be to use explode using " as the separator like this:

<?php
$res = explode('"','a:1:{s:14:"174.29.144.241";s:8:"20110508";}');
print_r($res);
?>

Any value in double quotes would be returned in an odd index i.e $res[1], $res[3]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜