Page 1 of 1

Regular expressions matching multi-lines

Posted: Sun Sep 12, 2004 12:26 pm
by hannahd
feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


Hello, I have a text file with two lines.

Code: Select all

line1
line2
I want to match line1, but it doesn't find it even though I've used the /m modifier. I thought this allowed strings to apply to lines.

Is this because I am using Windows and that o/s uses \r\n for line breaks?

Code: Select all

$filename = "file.txt";

$fp = fopen($filename, "r") or die("Cannot open file");

$str = fread($fp, filesize($filename));

$pattern = "/line1$/m";

if(preg_match($pattern, $str, $matches)) {

print "matched: ";

for($i=0; $i<count($matches); $i++) {
print "{$matches[$i]}";
}
}
else {

print "no match";

}

feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Sun Sep 12, 2004 12:40 pm
by feyd
you could just use [php_man]file[/php_man] or [php_man]fgets[/php_man]...

Posted: Sun Sep 12, 2004 1:23 pm
by hannahd
Thanks, I know I could do that, but the whole purpose is to learn regular expressions, and I wondered why it wouldn't work. :)

Posted: Sun Sep 12, 2004 1:39 pm
by feyd

Code: Select all

'#^(.*)$#m'

Posted: Sun Sep 12, 2004 2:16 pm
by hannahd
feyd wrote:

Code: Select all

'#^(.*)$#m'
Thanks :)

I don't understand what that does, though.

Posted: Sun Sep 12, 2004 2:34 pm
by feyd
match each line.