July 15, 2010

Split a string array into pieces

Question by arkchong

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

Answer by animuson

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

Answer by Starx

An example

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!