0

I am using a module to create booking orders in my website.

They have a hook I can use which fires after a new booking is created.

The variable I get is booking_form: Inside this variable is the following:

text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com

Is there someway in PHP to get all the values of all the fields in an array or something? So something like this?

array(
    name or name1? => PETER,
    secondname => SMITH,
    etc... => etc...
)

So the function has to split the string based on the ^ and ~ characters.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Senta
  • 193
  • 3
  • 16
  • There is an obvious pattern to use for `explode`: split by `~` to get form inputs, split by `^` to get `group => field => value`. – lolbas Jul 06 '18 at 10:14

3 Answers3

0

Try this :

$result = array();
$data = explode ( "~", $yourString )
foreach ( $data as $element)
{
    $elt = explode ( "^", $element ) ;
    $result[$elt[1]] = $elt[2];
}
0

Another way to do this...

$input = 'text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com';

$split = explode('~', $input);
$finalArray = [];

foreach($split as $thing) {
    list ($type, $key, $value) = explode('^', $thing);
    $finalArray[$key] = $value;
}

print_r($finalArray);
Dale
  • 10,384
  • 21
  • 34
0

Your formatted string seems inconsistently formatted and I don't understand the relevance of the text and email markers.

Furthermore, we don't know your input data may vary because you only gave us one and string AND we don't know your exact desired output because you "yatta-yatta"ed what you expect.

That said, parsing the string can be done with regex.

  • Match the text or email label followed by a literal caret
  • Capture one or more non-caret characters
  • Match a literal caret
  • Capture zero or more non-caret/non-tilde characters

Code: (Demo)

$string = 'text^name1^PETER~text^secondname1^SMITH~text^phone1^023482348~text^adres1^STREETAVENUE 1B~text^postcode1^91201CA~text^woonplaats1^LIVINGPLACE~email^email1^peter@example.com';

preg_match_all('/(?:text|email)\^([^^]+)\^([^^~]*)/', $string, $matches, PREG_SET_ORDER);
var_export(
    array_column($matches, 2, 1)
);

Output:

array (
  'name1' => 'PETER',
  'secondname1' => 'SMITH',
  'phone1' => '023482348',
  'adres1' => 'STREETAVENUE 1B',
  'postcode1' => '91201CA',
  'woonplaats1' => 'LIVINGPLACE',
  'email1' => 'peter@example.com',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136