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

Asked

Viewed 66 times

-2

I receive an array via POST which is generated from a field name="Referencia[]" of the form, the problem is that in this array there is information with comma.

Example: 2.7 cm, 3.1 cm.

I enter in the database separated by commas to be recovered using them, but in this case wrong separates.

I’d like to exchange the comma for '__' to use the implode generating 2,7 cm__3,1 cm and not delimiting by comma in this case.

Expected result:

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


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

NOTE: Currently the data is 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 would be to insert in the database already formatted like this: '7,7 cm__8,8 cm__9,8 cm'

  • 1

    I only regret the "being" not understand the question and negativar !

2 answers

1


To really do what you’re asking, you can use the function preg_match_all and locate 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 exit 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 is able to handle, also, with different units.

  • That expression saved, thank you @Anderson Carlos Woss

0

If the data is already in this pattern 2,7 cm, 3,1 cm and you’re sure that this pattern will always stay that way, so you could just use , (comma and space) as delimiter, so you wouldn’t need to modify anything in the form sending process.

In the explode() 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 not clear where you want to modify, whether it is in the form before sending or both sides. Finally, I have chosen to show a solution that is as simple as possible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.