tags:

views:

74

answers:

5

let said 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
)

Any idea? Thank in advanced

+5  A: 

the explode command:

explode(';', $array);

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

karlw
+2  A: 

An example

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

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] => ;
)
animuson
ops, sorry, what if i want to completely ignore the ";"?
arkchong
If you don't want the semicolon just delete that second foreach statement inside there.
animuson
A: 

Try this:

$a = "";

        foreach($array as $value) {
                flush();
                $a .= explode(";",$value);
        }
Jet
What is the purpose of that flush there? You don't flush a toilet when there's nothing in it...
animuson
+1  A: 
$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.

clumsyfingers