Home > Net >  PHP convert multiple strings with special chars as delimiters to array
PHP convert multiple strings with special chars as delimiters to array

Time:12-31

I have a multiple arrays with strings that comes out from a wordpress database. Its a table from a plugin that stores the data in a very strange way, like this:

    print_r($results);
    
Array 
(
    [form] => text^name14^Antony~text^secondname14^White~email^email14^[email protected]
)
Array  
(
    [form] => ......
)

I need to get the clean data, so:

foreach ($results as $result) {

    $formdata_array = explode('~',$result);
    $formdata_array_count = count($formdata_array);
    for ( $i=0 ; $i < $formdata_array_count ; $i  ) {
       if ( empty( $formdata_array[$i] ) ) {
          continue;
       }
       $elemnts = explode('^',$formdata_array[$i]);

       $type = $elemnts[0];
       $element_name = $elemnts[1];
       $value = $elemnts[2];
       $value = nl2br($value);
}

And at this point I get:

print_r($value)

    Antony 
    White
    [email protected]

But I need to have an array to work with

Array
    (
        [0] => Antony
        [1] => White
        [2] => [email protected]
    )

I triede differents methods like array_merge, array_column, array_combine but I can't get the final result

CodePudding user response:

This probably is what you are looking for:

<?php

$results = [
   ['form' => "text^name14^Antony~text^secondname14^White~email^email14^[email protected]"],
   ['form' => "text^name14^Georgy~text^secondname14^Black~email^email14^[email protected]"],
];

foreach ($results as $result) {
    $output = [];
    $formdata_array = explode('~',$result['form']);
    $formdata_array_count = count($formdata_array);
    for ( $i=0 ; $i < $formdata_array_count ; $i  ) {
       if ( empty( $formdata_array[$i] ) ) {
          continue;
       }
       $elements = explode('^',$formdata_array[$i]);

       $output[] = [
        'type' => $elements[0],
        'name' => $elements[1],
        'value' => $elements[2],
       ];
    }
   print_r(array_column($output, 'value'));
}

The output is:

Array
(
    [0] => Antony
    [1] => White
    [2] => [email protected]
)
Array
(
    [0] => Georgy
    [1] => Black
    [2] => [email protected]
)
  • Related