tags:

views:

291

answers:

5

How can I match everything with a PHP regular expression? I tried: /[.\r\n]*/, but it isn't working. Any ideas? Thanks.

This is for a method I made for a PHP class to parse e-mails:

public function getHeader($headerName) { 
    preg_match('/[\r\n]' . $headerName . '[:][ ](.+)[\r\n][^ \t]/Uis', "\n" . ltrim($this->originalMessage), $matches); return preg_replace('/[\r\n]*/', '', $matches[1]); 
    }
+1  A: 

What about /.*/s?

In a character class ( the [] ), . just means period.

Nathaniel Flath
That isn't matching new lines.
Yes, it is matching new lines: perl -e 'print "matches\n" if "\n" =~ m/\A.*\z/s'
depesz
+10  A: 

/.*/s (see perl's docs). The s option means (quoting from that URL):

Treat string as single line. (Make . match a newline)

Alex Martelli
+7  A: 

I assume, based on your inclusion of \n and \r above, that you want to match across multiple lines. In this case, use:

/.*/s

(note the explicit /s modifier, that is, change . to match any character whatsoever, even a newline, which it normally would not match.)

See http://www.perl.com/doc/manual/html/pod/perlre.html

vladr
This worked for what I needed! Thanks
A: 

Does /[\.\r\n]+/ do what you want?

This kludge has also worked for me before:

my $abstract_text = /Abstract:([\s\S]+?)\nReferences/m;

It's useful if you want to capture patterns with arbitrary text included or intervening between multiple captures.

bubaker
+3  A: 

Why do you want to match everything? There's no point in using it as a condition because it's always true. If you want to capture the text you don't need a regex to do it because you just use the entire string. If you're trying to get around taint-checking, then shame on you (and ask a separate question about doing that right).

Note that we have a bit of the XY Problem here. You have some task X in mind, and think Y is part of the solution. You ask about Y but never tell us X. It's hard to answer your real question when we don't know what you are trying to do. :)

brian d foy
It was for a method I made for a PHP class to parse e-mails: public function getHeader($headerName) { preg_match('/[\r\n]' . $headerName . '[:][ ](.+)[\r\n][^ \t]/Uis', "\n" . ltrim($this->originalMessage), $matches); return preg_replace('/[\r\n]*/', '', $matches[1]); }
You should update your question, not hide it in a comment :)
brian d foy
It sounds like your real question is "How do I extract email headers with PHP?". Surely there's a PHP class that already does that.
brian d foy