0

Hi I got the following string:

info:infotext,
dimensions:dimensionstext

and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.

I want to put the info as the key and he infotext as the value into an array like this:

Array {

[info] => infotext
[dimensions] => dimensionstext

}

2 Answers 2

1

Demo here

<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));   
foreach($array as $v)
{
  $o[$v[0]] = $v[1];
}
print_r($o);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use array_chunk and array_combine

    <?php
    $input  = 'info:infotext,
    dimensions:dimensionstext';

    $chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
    $result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

    print_r($result);   

http://ideone.com/dRtref

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.