1

I have a problem, I would like to ask for this string:

[NAME: abc] [EMAIL: [email protected]] [TIMEFRAME: 3 weeks] [BUDGET: 1000 dollars] [MESSAGE: bla bla bla]

Replace it with an array in the form:

array(
        'NAME'      => 'abc',
        'EMAIL'     => '[email protected]',
        '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 protected]] [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.

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.