2010-05-27 44 views
0

我有可能是两种形式之一的字符串:聪明的方式来有条件地拆分这个字符串?

prefix=key=value (which could have any characters, including '=') 

key=value 

所以我需要将它拆分无论是在第一或第二等号的基础上,布尔值被设置在其他地方。我这样做:

if ($split_on_second) { 
    $parts = explode('=', $str, 3); 
    $key = $parts[0] . '=' . $parts[1]; 
    $val = $parts[2]; 
} else { 
    $parts = explode('=', $str, 2); 
    $key = $parts[0]; 
    $val = $parts[1]; 
} 

这应该工作,但感觉不雅。有任何更好的想法在PHP? (我想有一个正则表达式忍者的方式来做到这一点,但我不是一个正则表达式忍者;-)

+4

使用正则表达式会导致两个问题。 – CMircea 2010-05-27 22:05:08

+0

OT:如果'value'可以包含'=',那么'$ val'赋值似乎是错误的...... – schnaader 2010-05-27 22:08:43

+0

您是否使用“prefix = key = vale”?如果你有选择,把事情改为“前缀:键=值”和“键=值”将使你的生活变得更加简单。 – 2010-05-27 22:11:11

回答

2

如何只

$parts = explode('=', $str); 
$key = array_shift($parts); 
//additionally, shift off the second part of the key 
if($split_on_second) 
{ 
    $key = $key . '=' . array_shift($parts); 
} 
//recombine any accidentally split parts of the value. 
$val = implode($parts, "="); 

另一个变化

$explodeLimit = 2; 
if($split_on_second) 
{ 
    $explodeLimit++; 
} 
$parts = explode('=', $str, $explodeLimit); 
//the val is what's left at the end 
$val = array_pop($parts); 
//recombine a split key if necessary 
$key = implode($parts, "="); 

并没有测试过这一点,但看起来它可能是其中的一个有趣的优化,使代码准确,但无法读取...

$explodeLimit = 2; 
//when split_on_second is true, it bumps the value up to 3 
$parts = explode('=', $str, $explodeLimit + $split_on_second); 
//the val is what's left at the end 
$val = array_pop($parts); 
//recombine a split key if necessary 
$key = implode($parts, "="); 
+0

从我+1,因为我们似乎有相同的想法:) – Amber 2010-05-27 22:16:12

+0

你的优化让我害怕。 :)如果$ split_on_second = 3呢? (理论上,它应该是一个严格的布尔值,但是用php,你永远不会知道,我想你可以把它放在一定的位置。)我可能会用'$ explodeLimit =($ split_on_second)来优化它吗? 3:2“。 – sprugman 2010-05-27 22:30:29

+0

我知道,C风格的真假是疯狂的可以利用的,对!它让我害怕,但手榴弹也是如此,军队仍在使用这些手榴弹! – Zak 2010-05-28 00:29:59

5

编辑:

现在我注意到,你得到了“如果前缀应该是有或没有“,在这种情况下,我原来的解决方案可能不太优雅。相反,我建议是这样的:

$parts = explode('=', $str); 
$key = array_shift($parts); 
if($has_prefix) { 
    $key .= '=' . array_shift($parts); 
} 
$val = implode('=', $parts); 

我原来的回应:

$parts = array_reverse(explode('=', $str)); 
$val = array_shift($parts); 
$key = implode('=', array_reverse($parts)); 
+0

@Amber击败我! +1的速度 – jcolebrand 2010-05-27 22:09:00

+0

实际上,我需要稍微修改它,因为$ key部分会被逆转atm。编辑:现在修正。 – Amber 2010-05-27 22:09:43

+0

好像这样会忽略$ value包含=号的情况 – Zak 2010-05-27 22:12:30

1
if ($prefix_exists) { 
    list($prefix, $str) = explode('=', $str, 2); 
    $prefix .= '='; 
} 

list($key, $val) = explode('=', $str, 2); 
$key = $prefix . $key; 
+0

这种变化似乎没有重组前缀和(子)键 – Zak 2010-05-27 22:18:15

+0

啊,谢谢,修正。 – 2010-05-27 22:23:08

+0

+1准确性:) – Zak 2010-05-27 22:26:09