PHP:拆分复杂字符串

时间:2012-12-05 19:59:50

标签: php regex

我正在尝试编写一个函数,它将获取一个字符串并创建一个下拉列表。

以下是一个示例字符串:

Primary[Blue|0000FF,Red|FF0000,Yellow|FFFF00],Secondary[Green|00FF00,Orange|FF9900,Purple|663399],Brown|A52A2A,Silver|C0C0C0

我想变成这个:

<select>
<optgroup label="Primary">
<option value="0000FF">Blue</option>
<option value="FF0000">Red</option>
<option value="FFFF00">Yellow</option>
</optgroup>
<optgroup label="Secondary">
<option value="00FF00">Green</option>
<option value="FF9900">Orange</option>
<option value="663399">Purple</option>
</optgroup>
<option value="A52A2A">Brown</option>
<option value="C0C0C0">Silver</option>
</select>

我一直在尝试将字符串转换为以下内容:

[0] => Primary
[0][0] => Blue|0000FF
[0][1] => Red|FF0000
[0][2] => Yellow|FFFF00
[1] => Secondary
[1][0] => Green|00FF00
[1][1] => Orange|FF9900
[1][2] => Purple|663399
[2]
[2][0] => Brown|A52A2A
[3]
[3][0] => Silver|C0C0C0

我不确定如何拆分初始字符串。我试过爆炸和preg_split,但似乎都没有分开我需要的地方。

2 个答案:

答案 0 :(得分:2)

不确定您是如何使用此字符串的,我建议您考虑json_decodejson_encode

对于当前格式,您可以使用:

$string = 'Primary[Blue|0000FF,Red|FF0000,Yellow|FFFF00],Secondary[Green|00FF00,Orange|FF9900,Purple|663399],Brown|A52A2A,Silver|C0C0C0';
preg_match_all("/([a-z]+)(\[([a-z0-9|,]+)\])|([a-z0-9|,]+)$/i", $string, $m);

printf("<select>");
for($i = 0; $i < count($m[1]); $i ++) {
    if (! empty($m[1][$i])) {
        printf("\n\t<optgroup label=\"%s\">", $m[1][$i]);
        foreach ( array_filter(explode(",", $m[3][$i])) as $var ) {
            list($color, $hex) = explode("|", $var);
            printf("\n\t\t<option value=\"%s\">%s</option>", $hex, $color);
        }
        printf("\n\t</optgroup>");
    }
}
foreach ( array_filter(explode(",", $m[4][2])) as $var ) {
    list($color, $hex) = explode("|", $var);
    printf("\n\t<option value=\"%s\">%s</option>", $hex, $color);
}
printf("\n</select>");

输出

<select>
    <optgroup label="Primary">
        <option value="0000FF">Blue</option>
        <option value="FF0000">Red</option>
        <option value="FFFF00">Yellow</option>
    </optgroup>
    <optgroup label="Secondary">
        <option value="00FF00">Green</option>
        <option value="FF9900">Orange</option>
        <option value="663399">Purple</option>
    </optgroup>
    <option value="A52A2A">Brown</option>
    <option value="C0C0C0">Silver</option>
</select>

答案 1 :(得分:0)

您可以尝试拆分this regex(?![^\[]+\]),

然后从那里查看该字符串是否包含[]

$array = preg_split('/(?![^\[]+\]),/', $string);

$return = array();

foreach($array as $val){
    if(preg_match('/(.*)\[(.*)\]/', $val, $match) === 1){
        $return[$match[1]] = explode(',', $match[2]);
    }
    else{
        $return[] = $val;
    }
}

DEMO:http://ideone.com/BM0ewX