Search code examples
phparraystext-parsinginline-styles

Parse inline style declaration string to array


Let's say I have an array that store like this:

Array ( 
   [0] => width: 650px;border: 1px solid #000; 
   [1] => width: 100%;background: white; 
   [2] => width: 100%;background: black; 
) 

How should I make the array[0] string split into piece by separated the ";"? Then I want to save them in array again, or display them out. How should I do it?

Array(
   [0] => width: 650px
   [1] => border: 1px solid #000
)

Solution

  • I would personally use the preg_split to get rid of that extra array element that would occur from the final semicolon...

    $newarray = array();
    foreach ($array as $i => $styles):
        // Split the statement by any semicolons, no empty values in the array
        $styles = preg_split("/;/", $styles, -1, PREG_SPLIT_NO_EMPTY);
        // Add the semicolon back onto each part
        foreach ($styles as $j => $style) $styles[$j] .= ";";
        // Store those styles in a new array
        $newarray[$i] = $styles;
    endforeach;
    

    Edit: Don't add the semicolon to each line:

    $newarray = array();
    foreach ($array as $i => $styles):
        // Split the statement by any semicolons, no empty values in the array
        $newarray[$i] = preg_split("/;/", $styles, -1, PREG_SPLIT_NO_EMPTY);
    endforeach;
    

    Which should output:

    Array(
       [0] => width: 650px;
       [1] => border: 1px solid #000;
    )
    

    Unlike explode, which should output:

    Array(
       [0] => width: 650px;
       [1] => border: 1px solid #000;
       [2] => ;
    )