0

我正在处理大量数据,并试图返回其中包含字符串“INFO:”的所有行。我已经设法让模式返回我感兴趣的数据,但想知道如何改进这个正则表达式模式以省略我正在匹配的字符串(以及如果可能的空格),所以只返回我感兴趣的实际数据。

$pattern = "/^.*INFO:.*\$/m";
preg_match_all($pattern, $content, $matches);

INFO:   framerate             25.00
INFO:   width                 480.00
INFO:   height                360.00
INFO:   audioinputvolume      75.00
INFO:   audiocodecid          mp4a
INFO:   audiodatarate         48.00
4

3 回答 3

2
preg_match_all('/^INFO:\s+([^\s]+)\s+([^\s]+)$/ms', $content, $matches);

回报:

Array
(
    [0] => Array
        (
            [0] => INFO:   framerate             25.00
            [1] => INFO:   width                 480.00
            [2] => INFO:   height                360.00
            [3] => INFO:   audioinputvolume      75.00
            [4] => INFO:   audiocodecid          mp4a
            [5] => INFO:   audiodatarate         48.00
        )

    [1] => Array
        (
            [0] => framerate
            [1] => width
            [2] => height
            [3] => audioinputvolume
            [4] => audiocodecid
            [5] => audiodatarate
        )

    [2] => Array
        (
            [0] => 25.00
            [1] => 480.00
            [2] => 360.00
            [3] => 75.00
            [4] => mp4a
            [5] => 48.00
        )

)

请注意,这两个字段都不允许有空格。

于 2012-05-11T20:35:37.363 回答
1
$pattern = "/INFO:\s+(.*?)\s+(.*?)(\s|$)/m";

这应该够了吧。括号中匹配的内容将作为元素出现在 $matches[1] 和 $matches[2]

以下是这将输出的内容:

Array
(
[0] => Array
    (
        [0] => INFO:   framerate             25.00

        [1] => INFO:   width                 480.00

        [2] => INFO:   height                360.00

        [3] => INFO:   audioinputvolume      75.00

        [4] => INFO:   audiocodecid          mp4a

        [5] => INFO:   audiodatarate         48.00
    )

[1] => Array
    (
        [0] => framerate
        [1] => width
        [2] => height
        [3] => audioinputvolume
        [4] => audiocodecid
        [5] => audiodatarate
    )

[2] => Array
    (
        [0] => 25.00
        [1] => 480.00
        [2] => 360.00
        [3] => 75.00
        [4] => mp4a
        [5] => 48.00
    )

[3] => Array
    (
        [0] => 

        [1] => 

        [2] => 

        [3] => 

        [4] => 

        [5] => 
    )

)

所有空格/行尾字符都有第三个数组,因为我使用括号来使用 | 操作员说空格或文本的结尾可以匹配。

于 2012-05-11T20:34:26.100 回答
0

将您有兴趣匹配的组放入子模式中 ( )

我认为在您的情况下,它看起来像:

$pattern = "/^.*INFO:(.*)\$/m";

现在您可以使用以下命令查看括号中的内容$matches[1][$match]

于 2012-05-11T20:34:41.403 回答