将字符串拆分为数组

时间:2011-09-06 21:45:39

标签: php regex arrays

我无法将此字符串拆分为我需要的模式中的数组。字符串是:

ATTRIBUTE1: +VALUE1;
ATTRIBUTE2: -VALUE2%;

我基本上需要这样的数组:

array (
    [0] => "ATTRIBUTE1", 
    [1] => "+", 
    [2] => "VALUE1", 
    [3] => "%"
)
array (
    [0] => "ATTRIBUTE2", ...
)

“%”是可选的,但+/-符号不是。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

您可以使用正则表达式:

$text= "ATTRIBUTE1: +VALUE1;\nATTRIBUTE2: -VALUE2%;";
echo "STRING\n" . $text . "\n\n";

preg_match_all("~
                ^             # match start of line
                ([^:]+):\s*   # match anything that's not a ':' (attribute), followed by a colon and spaces
                ([+-])        # match a plus or a minus sign
                ([^%;]+)      # match anything that's not a '%' or ';' (value)
                (%?)          # optionally match percent sign 
                ;\s*$         # match ';' then optional spaces and end of line
                ~mx", $text, $matches, PREG_SET_ORDER);

print_r($matches);

打印:

STRING
ATTRIBUTE1: +VALUE1;
ATTRIBUTE2: -VALUE2%;

Array
(
    [0] => Array
        (
            [0] => ATTRIBUTE1: +VALUE1;
            [1] => ATTRIBUTE1
            [2] => +
            [3] => VALUE1
            [4] => 
        )

    [1] => Array
        (
            [0] => ATTRIBUTE2: -VALUE2%;
            [1] => ATTRIBUTE2
            [2] => -
            [3] => VALUE2
            [4] => %
        )

)

你可能不得不玩正则表达式,但它现在有了评论所以不应该太难以弄明白。

答案 1 :(得分:-1)

你可以做的一件事:

$str=explode(": ",$str);
$array[0]=$str[0];
$array[1]=substr($str[1],0,1);
if(substr($str[1],strlen($str[1])-1)=="%"){
    $array[2]=substr($str[1],1,strlen($str[1])-2);
    $array[3]="%";
}else
    $array[2]=substr($str[1],1);