php从字符串中提取值
我有一个包含以下字符串的会话变量。
a:2:{s:7:"LoginId";s:32:"361aaeebef992bd8b57cbf390dcb3e8d";s:8:"Username";s:6:"aaaaaa";}
我想提取用户名“aaaaaa”的值。谁能建议更简单/更有效的方式?
$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
$session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
$temp = $session_user_array[3];
$temp = explode(':', $temp);
$username = $temp[2];
echo $username;
它变得更丑了......不得不删除引号。
if ($_SESSION["SecurityAccess_CustomerAccess"]){
$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
$session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
$temp = $session_user_array[3];
$temp = explode(':', $temp);
$temp = str_replace("\"", "", $temp[2]);
$username = $temp;
echo $username ;
}
I have a session variable that contains the following string.
a:2:{s:7:"LoginId";s:32:"361aaeebef992bd8b57cbf390dcb3e8d";s:8:"Username";s:6:"aaaaaa";}
I want to extract the value of username "aaaaaa". can anyone suggest easier/more efficient manner?
$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
$session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
$temp = $session_user_array[3];
$temp = explode(':', $temp);
$username = $temp[2];
echo $username;
It just got uglier... had to removed quotes.
if ($_SESSION["SecurityAccess_CustomerAccess"]){
$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
$session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
$temp = $session_user_array[3];
$temp = explode(':', $temp);
$temp = str_replace("\"", "", $temp[2]);
$username = $temp;
echo $username ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是您所需要的:
您的会话数据是以 序列化 形式存储的数组,因此反序列化会将其变成返回到常规 PHP 数组。
This is all you need:
Your session data is an array stored in serialized form, so unserializing it turns it back into a regular PHP array.
如果数据总是以类似的方式形成,我建议使用正则表达式。
If the data will always be formed in a similar manner, I would suggest using a regular expression.
如果这些值的位置始终相同,您可能可以编写某种类型的正则表达式来帮助解决其中的一些问题。但我认为这里的内容非常适合可读性。如果有人追随你,他们就会很清楚你想要实现的目标。像这样的字符串的正则表达式可能不会产生相同的效果。
You could probably write a some type of regular expression to help with some of this if the placement of these values were always the same. But I think what you have here is great for readability. If anyone came after you they would have a good idea of what you are trying to achieve. A regular expression for a string like this would probably not have the same effect.