聪明的方式有条件地分裂这个字符串?

时间:2010-05-27 22:03:30

标签: php parsing string

我有一个字符串可以是两种形式之一:

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中有任何更好的想法? (我想有一种正则表达式 - 忍者的方法,但我不是一个正则表达式的忍者。; - )

3 个答案:

答案 0 :(得分: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));

答案 1 :(得分: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, "=");

答案 2 :(得分:1)

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

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