douwen3362 2013-05-01 12:11
浏览 104
已采纳

PHP regex preg_match_all:在多个方括号之间捕获文本

I need to capture some string arrays.. and i've been trying but i can't :$

i've this in my code:

<?php
$feed = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
preg_match_all("/\[(.*?)\]/",$feed,$matches);
print_r($matches);

and is returning:

Array
(
    [0] => Array
        (
            [0] => [['2013/04/03',8.300]
            [1] => ['2013/04/04',8.320]
            [2] => ['2013/04/05',8.400]
        )

    [1] => Array
        (
            [0] => ['2013/04/03',8.300
            [1] => '2013/04/04',8.320
            [2] => '2013/04/05',8.400
        )

)

how can i make with preg_match_all or preg_split.. or whatever method is needed to return one array of elements like the $matches[1][1] or $matches[1][2]??

i mean the format of each element should be:

'2013/04/05',8.400

hope to be clear :)

and thanks in advance!!

  • 写回答

3条回答 默认 最新

  • douna1895 2013-05-01 12:59
    关注

    This text appears to be in fairly normalized format, ala JSON. It's entirely possible to avoid reg matching and parse this with json_decode, albeit some minor transformations have to be made.

    // original input
    $text = "[['2013/04/03',8.300],['2013/04/04',8.320],['2013/04/05',8.400]]";
    
    // standard transformation to correct ' and / characters
    $text = str_replace( array('/', "'"), array('\/', '"'), $text );
    
    // let native PHP take care of understanding the data
    $data = json_decode( $text );
    

    This gives you the array of arrays, containing your dates and values. print_r( $data ); gives:

    Array (
        [0] => Array (
            [0] => 2013/04/03
            [1] => 8.3
        )
        [1] => Array (
            [0] => 2013/04/04
            [1] => 8.32
        )
        [2] => Array (
            [0] => 2013/04/05
            [1] => 8.4
        )
    )
    

    The transformations are replacing / to \/ and ' to " to make the string JSON-compliant. Or something to that effect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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