0

I already tried looking 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!!!!

1
  • try this ^C\s\d\s\w+\r\w+ Commented May 10, 2011 at 7:55

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

O_O DON'T tell me that... i've been rewriting that expression for 5 hours!!! :S, so.. if it doesn't work... then... is it the server??, PHP 5.1.6... oh my... this is bad :( my print_r only show me the first set :(
yay, it works!... also... I'm reading the text from a POP server... and I send the text from gmail... this time i sent it using Plain Text... could that be a problem too?? thanks!!!
@figus, maybe, but I can't tell for sure. Anyway, good to hear it works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.