Turning the text of a variable into an array

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 fetch a function from the link but could not find something to do that. does anyone remember some function to do this?

    
asked by anonymous 03.11.2015 / 03:20

2 answers

2

Thanks for everyone's help. I was able to solve this problem permanently 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>';
    
03.11.2015 / 04:18
2

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

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];
}
    
03.11.2015 / 03:32