Page 1 of 1

Howto Regular Expression

Posted: Sun Sep 10, 2006 12:45 am
by kahwooi
I have a string: 'sessUserIdx|s:2:"11";sessUserName|s:6:"kelvin";sessUserFullName|s:6:"Kelvin";'

How do I use preg to retrieve the sessUserIdx value = 11, the problem is the sessUserIdx can be located in different location in the string.

Thank you.

Posted: Sun Sep 10, 2006 12:55 am
by feyd
You may want to look at the database sessions thread linked from Useful Posts.. it has an extraction function specifically for this format.

Posted: Sun Sep 10, 2006 1:13 am
by kahwooi
With this info, I want to know number and who is online.

Posted: Sun Sep 10, 2006 2:07 am
by n00b Saibot
feyd wrote:You may want to look at the database sessions thread linked from Useful Posts.. it has an extraction function specifically for this format.
also since that is a serialized array.. you may try loading (unserializing) the array and acces the sessUserIdx key directly...

Posted: Sun Sep 10, 2006 4:46 am
by kahwooi
n00b Saibot, good idea, I will try it out.

Posted: Mon Sep 11, 2006 9:29 am
by kahwooi
$field = 'sessUserIdx|s:2:"11"';
preg_match("/\"[^\"\/]+/", $field, $userIdxValue);

I get this result = "11, I have no idea how to retrieve only 11, please help, I'm weak at regular expression.

Posted: Mon Sep 11, 2006 10:34 am
by Mordred
kahwooi wrote:

Code: Select all

$field = 'sessUserIdx|s:2:"11"';
preg_match("/"[^"\/]+/", $field, $userIdxValue);
I get this result = "11, I have no idea how to retrieve only 11, please help, I'm weak at regular expression.
1. Use a different delimiter, one that is easy to read and wouldn't clash with commonly or specifically used characters in the regex. My personal faveourite is ~

Code: Select all

$field = 'sessUserIdx|s:2:"11"';
preg_match("~"([^"]+)~", $field, $userIdxValue);
var_dump($userIdxValue[1]);

Posted: Mon Sep 11, 2006 10:40 am
by sweatje
this may be what you are looking for, expressed as a SimpleTest test:

Code: Select all

function testReplicateUnserialize() {
	$str = 'sessUserIdx|s:2:"11";sessUserName|s:6:"kelvin";sessUserFullName|s:6:"Kelvin";';
	$desired = array('sessUserIdx' => '11', 'sessUserName' => 'kelvin', 'sessUserFullName' => 'Kelvin');
	$regex = '/(?:^|;)([^|]+)\|s:\d+:"([^"]*)"/';
	if (preg_match_all($regex, $str, $match)) {
		$result = array_combine($match[1], $match[2]);
	}
	$this->assertEqual($desired, $result);
}

Posted: Mon Sep 11, 2006 10:59 am
by GM
Quick on-topic question...

Does anyone know why the session variables are not serialised using the standard "serialise" function? It seems strange to me that the session string can't be unserialised normally, and was just wondering what the reason might be.

Posted: Mon Sep 11, 2006 3:14 pm
by feyd
I would suspect it has to do with its previous incarnation as working with register_globals and not being an array.