Alper
Alper

Reputation: 107

Splitting a string into an array

I'm having trouble splitting this string into an array in the pattern I need it to be. The string is:

ATTRIBUTE1: +VALUE1;
ATTRIBUTE2: -VALUE2%;

I essentially need an array like this:

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

The "%" is optional, but the +/- sign is not. Any help would be appreciated!

Upvotes: 2

Views: 112

Answers (2)

NullUserException
NullUserException

Reputation: 85478

You could use regex:

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

Prints:

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] => %
        )

)

You might have to play around with the regex, but it's got comments now so it shouldn't be too hard to figure it out.

Upvotes: 3

Tim Withers
Tim Withers

Reputation: 12059

One thing you could do:

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

Upvotes: -1

Related Questions