Howto Regular Expression
Moderator: General Moderators
Howto Regular Expression
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.
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.
- n00b Saibot
- DevNet Resident
- Posts: 1452
- Joined: Fri Dec 24, 2004 2:59 am
- Location: Lucknow, UP, India
- Contact:
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 ~kahwooi wrote:I get this result = "11, I have no idea how to retrieve only 11, please help, I'm weak at regular expression.Code: Select all
$field = 'sessUserIdx|s:2:"11"'; preg_match("/"[^"\/]+/", $field, $userIdxValue);
Code: Select all
$field = 'sessUserIdx|s:2:"11"';
preg_match("~"([^"]+)~", $field, $userIdxValue);
var_dump($userIdxValue[1]);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);
}