I have a problem, I would like to ask for this string:
[NAME: abc] [EMAIL: email@gm.com] [TIMEFRAME: 3 weeks] [BUDGET: 1000 dollars] [MESSAGE: bla bla bla]
Replace it with an array in the form:
array(
'NAME' => 'abc',
'EMAIL' => 'email@gm.com',
'TIMEFRAME' => '3 weeks',
'BUDGET' => '1000 dollars',
'MESSAGE' => 'bla bla bla' );
I tried to do something like this:
$content = str_replace(array('[', ']'), '', '[NAME: abc] [EMAIL: email@gm.com] [TIMEFRAME: 3 weeks] [BUDGET: 1000 dollars] [MESSAGE: bla bla bla]');
preg_match_all('/[A-Z]+\:/', $content, $inputs);
I managed to pull out the "keys", but I do not know how to pull out their "values". Any ideas?
Thank you in advance for your help and I apologize for my English.
You may use the following regex:
'~\[(\w+):\s*([^][]*)]~'
See the regex demo.
Details
\[
- a [
char(\w+)
- Group 1: 1+ letters, digits or _
:
- a colon\s*
- 0+whitespaces([^][]*)
- Group 2: 0+ chars other than [
and ]
]
- a ]
char.See the PHP demo:
$s = "[NAME: abc] [EMAIL: cde] [TIMEFRAME: efg] [BUDGET: hij] [MESSAGE: klm]";
if (preg_match_all('~\[(\w+):\s*([^][]*)]~', $s, $m)) {
array_shift($m); // Removes whole match values from array
print_r(array_combine($m[0], $m[1])); // Build the result with keys (Group 1) and values (Group 2)
}