1

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

这是一个示例字符串:

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

我不确定如何拆分初始字符串。我尝试了explode和preg_split,但似乎都没有在我需要的地方分裂。

4

2 回答 2

2

json_decode不知道你是怎么用这个字符串结束的,我建议你考虑一下json_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>
于 2012-12-05T20:09:03.697 回答
0

您可以尝试在此正则表达式上拆分: (?![^\[]+\]),

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

$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;
    }
}

演示:http: //ideone.com/BM0ewX

于 2012-12-05T20:17:37.113 回答