doushu5451 2018-05-28 04:06
浏览 39
已采纳

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

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条回答 默认 最新

  • duanlang1196 2018-05-28 04:29
    关注

    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
    ";
    echo "word1value = $word1value
    ";
    echo "word2 = $word2
    ";
    echo "word2value = $word2value
    ";
    echo "word3 = $word3
    ";
    echo "word3value = $word3value
    ";
    

    Output:

    word1 = PHYSICAL
    word1value = 3.8
    word2 = ORGANIZATIONAL
    word2value = 4
    word3 = TECHNICAL
    word3value = 2.9
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line