1

I have a variable in php that has the following value:

var $line="'PHYSICAL':3.8,'ORGANIZATIONAL':4,'TECHNICAL':2.9"; 

From that line variable, I want to extract each word and values in php, so basically I want something like below:

var $word1=PHYSICAL;
var $word1value=3.8;
var $word2=ORGANIZATIONAL;
var $word2value=4;
var $word3=TECHNICAL;
var $word3value=2.9;

I want to capture all the words and values separately in different variables, so that later I can process them. Can anyone please assist me on this. Thanks.

1
  • can't you just use arrays? Commented May 28, 2018 at 4:19

1 Answer 1

3

The simplest way to do this is with preg_split. You can use the PREG_SPLIT_DELIM_CAPTURE flag to enable capturing the word without the surrounding quotes, and PREG_SPLIT_NO_EMPTY to remove the empty values that arise from this particular split pattern.

$line="'PHYSICAL':3.8,'ORGANIZATIONAL':4,'TECHNICAL':2.9"; 
$array = preg_split("/'([^']+)':|,/", $line, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($array);

Output:

Array
(
    [0] => PHYSICAL
    [1] => 3.8
    [2] => ORGANIZATIONAL
    [3] => 4
    [4] => TECHNICAL
    [5] => 2.9
)

You can then post-process the array (for example using array_filter and array_combine) to produce something which might be more useful:

$newarray = array_combine(array_filter($array, function ($i) { return !($i % 2); }, ARRAY_FILTER_USE_KEY),
                          array_filter($array, function ($i) { return $i % 2; }, ARRAY_FILTER_USE_KEY));
print_r($newarray);

Output:

Array
(
    [PHYSICAL] => 3.8
    [ORGANIZATIONAL] => 4
    [TECHNICAL] => 2.9
)

If you really want the individual variables you can do this:

for ($i = 0; $i < count($array); $i += 2) {
    ${'word' . intdiv($i+2, 2)} = $array[$i];
    ${'word' . intdiv($i+2, 2) . 'value'} = $array[$i+1];
}
echo "word1 = $word1\n";
echo "word1value = $word1value\n";
echo "word2 = $word2\n";
echo "word2value = $word2value\n";
echo "word3 = $word3\n";
echo "word3value = $word3value\n";

Output:

word1 = PHYSICAL
word1value = 3.8
word2 = ORGANIZATIONAL
word2value = 4
word3 = TECHNICAL
word3value = 2.9
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you so much. This works perfectly fine. I appreciate your help.
That's great, glad to help. I've also (since I was in the process of typing when you accepted the answer) added a way to get the individual variables you described in your question.

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.