从php字符串中捕获特定的字符串和值

时间:2018-05-28 04:06:57

标签: php

我在php中有一个具有以下值的变量:

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

从那个行变量,我想在php中提取每个单词和值,所以基本上我想要如下所示:

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

我想在不同的变量中分别捕获所有单词和值,以便稍后我可以处理它们。任何人都可以帮助我。谢谢。

1 个答案:

答案 0 :(得分:3)

最简单的方法是使用preg_split。您可以使用PREG_SPLIT_DELIM_CAPTURE标记来启用捕获单词而不使用周围的引号,并使用PREG_SPLIT_NO_EMPTY删除由此特定拆分模式产生的空值。

$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);

输出:

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

然后,您可以对数组进行后处理(例如使用array_filterarray_combine)来生成可能更有用的内容:

$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);

输出:

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

如果你真的想要个别变量,你可以这样做:

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";

输出:

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