Transform the text of a variable into an array

Asked

Viewed 58 times

0

I’m using php.

I have the following text in a variable:

X-Inquiry-Name: analia felices

X-Inquiry-Adults: 5

X-Inquiry-Children: 10

I would like to be transforming into an array, separating these two points, more or less as an example below:

array (

[X-Inquiry-Name] => analia felices

[X-Inquiry-Adults] => 5

[X-Inquiry-Children] => 10

)

I tried to find a function on http://php.net but I couldn’t find anything to do it. Someone remembers some function to do it?

2 answers

2

What you basically have a string is a pattern X-Inquiry-.
The function preg_match_all search for all patterns present in the string, according to the regex passed.

preg_match_all('/(X-Inquiry-\w+):(.*)/', $str, $match);
// X-Inquiry- é seu padrão ele sempre deve procurar por isso
// \w+ busca por qualquer coisa que seja [a-zA-Z0-9_]
// (X-Inquiry-\w+) é um grupo de captura
// : deve capturar sempre 
// (.*) é o segundo grupo de captura que busca qualquer coisa

// $match terá o indice `1` representado pelo grupo 1
// e indice `2`  representado pelo grupo 2

$newArray = array();
// o foreach foi usado para unir os "match" em chave, valor
foreach($match[1] as $k => $value){
    $newArray[$value] = $match[2][$k];
}
  • I recommend that you explain the code, should the author need to make any modification in case of another need, I’m sure that will take my comment as a constructive criticism.

  • Good evening William, Your code has worked, now I have a difficulty, in one of the items this appearing wrong inside him has 2 two points. -

  • Opa, sorry, my script looks like this: preg_match_all('/(.): (.)/', $emailStructure2, $match);

  • Thanks for the help, I got it.

2


Thanks for all your help. I was able to solve definitively with the following code:

preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $emailStructure2, $match);
$newArray = array();
foreach($match[1] as $k => $value){
$newArray[$value] = $match[2][$k];
}echo '<pre>';
print_r($newArray);
echo '</pre>';

Browser other questions tagged

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