How to change the delimiter of the Php array obtained via POST, replacing the comma?

-2

I get a array via POST which is generated from a% field of the form, the problem is that this array has information with a comma.

Example: 2.7 cm, 3.1 cm.

I enter the database separated by commas to be retrieved using them, but in this case it goes wrong.

I would like to change the comma to '__' to use implode generating name="Referencia[]" and not comma delimiting in this case.

Expected result:

$MyArray = explode("__", array_filter( $_POST['Referencia'] ) );


echo $MyArray; // 2,7 cm__3,1

NOTE: The data is currently inserted in this format ' 7,7 cm, 8,8 cm, 9,8 cm , , the solution can be made in the form or after sending, but the interesting thing would be to insert into the database already formatted like this: ' 7,7 cm__8,8 cm__9,8 cm '

    
asked by anonymous 16.03.2017 / 15:25

2 answers

1

To really do what you're asking, you can use the preg_match_all and find the appropriate values with a regular expression:

$reference = "2,7 cm, 3,1 cm, 20,0 dm, 0,89 m, 0,0001 km";

if (preg_match_all("/[0-9]+\,[0-9]+ [a-zA-Z]+/", $reference, $matches))
{
  print_r($matches);
}

The output will be:

Array
(
    [0] => Array
        (
            [0] => 2,7 cm
            [1] => 3,1 cm
            [2] => 20,0 dm
            [3] => 0,89 m
            [4] => 0,0001 km
        )

)

Then just do: implode("__", $matches[0]) to have:

2,7 cm__3,1 cm__20,0 dm__0,89 m__0,0001 km 
  

Note that this way the program can also handle different units.

    
16.03.2017 / 16:31
0

If the data already is in this 2,7 cm, 3,1 cm pattern, and you are sure that this pattern will always remain that way, then you could just use% com_and% as a delimiter so you would not have to change anything in the sending process of the form.

No , would look something like this

$MyArray = explode(", ", array_filter( $_POST['Referencia'] ) );

The array will be

array(
    2,7 cm,
    3,1 cm
)

This seems to be the least invasive and clean way.

It is unclear where you want to modify, whether it is on the pre-submission form or the two sides. Finally, I have chosen to show a solution that is as simple as possible.

    
16.03.2017 / 16:11