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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?