'Split a string array into pieces

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 1:[1]

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

Solution 2:[2]

the explode command:

explode(';', $array);

You'll then have to append the ';' to the end of each string.

Solution 3:[3]

An example

foreach($array as $item) {
   $mynewarray = explode(";",$item);
   foreach($mynewarray as $newitem) {
        $finalarray[] = $newitem.";";
   }
   //array is ready
}

Solution 4:[4]

$arr = array('width: 650px;border: 1px solid #000;','width: 100%;background: white;','width: 100%;background: black;');

$arr = explode(';',implode(';',$arr));
for($i=0; $i < sizeof($arr)-1; $i++) { $arr[$i] .= ';'; }

print_r($arr);

Will print all of the semi-colon separated lines as separate entities in the array... +1 empty entry which you can delete.

Solution 5:[5]

Try this:

$a = "";

        foreach($array as $value) {
                flush();
                $a .= explode(";",$value);
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 karlw
Solution 3 Starx
Solution 4 clumsyfingers
Solution 5 Jet