doushu5451 2018-05-27 20: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-27 20: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
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥40 selenium访问信用中国
  • ¥15 电视大赛投票系统的c语言代码怎么做
  • ¥20 在搭建fabric网络过程中遇到“无法使用新的生命周期”的报错
  • ¥15 Python中关于代码运行报错的问题
  • ¥500 python 的API,有酬谢
  • ¥15 软件冲突问题,软件残留问题
  • ¥30 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
  • ¥50 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
  • ¥15 alpha101因子里哪些适合crypto?
  • ¥15 ctrl win alt 键一直触发
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部