开发者

Multiline PHP Regex problem

I already tried look开发者_高级运维ing here and in google... but I can't figure out what am I doing wrong :(

I have this text:

C 1 title
comment 1

C 2 title2
comment 2

C 3 title3
comment 3

Now... What I want to do is

  1. Check for the C at the beggining.
  2. Capture the number
  3. Capture the Tile
  4. Capture the comment

I'm trying to use this expression:

preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match);

but it only works for the first set =(

Any tip on what am I doing wrong???

Thanks!!!!


It works as expected.

The snippet:

<?php
$body = 'C 1 title
comment 1

C 2 title2
comment 2

C 3 title3
comment 3';

preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match);

print_r($match);
?>

produces the following output:

Array
(
    [0] => Array
        (
            [0] => C 1 title
comment 1
            [1] => C 2 title2
comment 2
            [2] => C 3 title3
comment 3
        )

    [1] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            )

    [2] => Array
        (
            [0] => title
            [1] => title2
            [2] => title3
        )

    [3] => Array
        (
            [0] => comment 1
            [1] => comment 2
            [2] => comment 3
        )

)

as you can see on Ideone.

To keep your matches nicely grouped, you might want to try:

preg_match_all("/^C (\d*) (.*)\n(.*)$/im", $body, $match, PREG_SET_ORDER);

instead.

HTH

EDIT

Ideone runs: PHP Version => 5.2.12-pl0-gentoo

And I also tested it on my machine (and get the same result), which runs: PHP Version => 5.3.3-1ubuntu9.5

But I can't imagine this is a versioning thing (at least, not with 5.x versions). Perhaps your line breaks are Windows style? Try this regex instead:

"/^C +(\d*) +(.*)\r?\n(.*)$/im"

I used the line break \r?\n instead of just \n so that Windows and Unix-style line breaks are matched, and also replaced single spaces with + to account for possible two (or more) spaces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜