Simon
Simon

Reputation: 23151

Dot doesn't match new lines?

When I write a regex with . in it, it doesn't match new lines.

preg_match('/.*+?/') ...

What do I need to write, to match all possible characters, and new lines too?

Upvotes: 6

Views: 3189

Answers (5)

Jet
Jet

Reputation: 1325

Try this:

   \r : carriage return
   \n : new line 
   \w : even [a-zA-Z0-9_] 
   *  : 0 or more. even :  +?
   $text = "a\nb\n123"; 
   preg_match("/[\w\r\n]*/i", $text, $match);
   print_r($match);

vide this list:

http://i26.tinypic.com/24mxgt4.png

Upvotes: 0

Freyja
Freyja

Reputation: 40884

The . does not match new lines - and that is on purpose (though I am not really sure why). You would use the s modifier to change this behaviour, and make . match all characters, including the newline.

Example:

$text = "Foobar\n123"; // This is the text to match

preg_match('/^Foo.*\d+$/', $text); // This is not a match; the s flag isn't used
preg_match('/^Foo.*\d+$/s', $text); // This is a match, since the s flag is used

Upvotes: 1

NikiC
NikiC

Reputation: 101936

Apart from the s modifier you should think about using a negated character class. Instead of

 #http://example\.org/.+/.+/.+#

you may use

 #http://example\.org/[^/]+/[^/]+/[^/]+#

which ought to be faster.

Upvotes: 0

kennytm
kennytm

Reputation: 523494

Add the s modifier, e.g.

'/./s'

Upvotes: 23

Cocowalla
Cocowalla

Reputation: 14340

By default . will not match newlines. You can change this behaviour with the s modifier.

Upvotes: 2

Related Questions