Regx to remove all characters after a match

D

Duke of Hazard

I can not figure out why this is not printing just 123:

$name = "123\n456\n789";

$name =~ s/\n.*//;

print $name;

which outputs:

123
789

If I write it in php using preg_replace , it works!
 
J

John W. Krahn

Duke said:
I can not figure out why this is not printing just 123:

$name = "123\n456\n789";

$name =~ s/\n.*//;

print $name;

which outputs:

123
789

That is because . matches any character *except* newline. If you want
it to match a newline as well then you have to use the /s option:

$name =~ s/\n.*//s;


John
 
G

Gunnar Hjalmarsson

Eric said:
By default, '.' in Perl regexes does not match newline. If you want it
to match newline, use

$name =~ s/\n.*//s;

I don't know PHP, but it surprises me that it handles that case
differently.

A bug in PHP?
 
G

Gunnar Hjalmarsson

Abigail said:
Gunnar Hjalmarsson ([email protected]) wrote on VCCCXLIV September
MCMXCIII in <URL:~~ Eric Amick wrote:
~~ > On Thu, 17 Apr 2008 20:23:23 -0700 (PDT), Duke of Hazard
~~ >
~~ >> I can not figure out why this is not printing just 123:
~~ >>
~~ >> $name = "123\n456\n789";
~~ >>
~~ >> $name =~ s/\n.*//;
~~ >>
~~ >> print $name;
~~ >>
~~ >> which outputs:
~~ >>
~~ >> 123
~~ >> 789
~~ >>
~~ >> If I write it in php using preg_replace , it works!
~~ >
~~ > By default, '.' in Perl regexes does not match newline. If you want it
~~ > to match newline, use
~~ >
~~ > $name =~ s/\n.*//s;
~~ >
~~ > I don't know PHP, but it surprises me that it handles that case
~~ > differently.
~~
~~ A bug in PHP?

It would do what the OP intended in Perl6 as well.

Maybe so, but the PHP docs say:

".
match any character except newline (by default)"

And still:

$ cat test.php
#!/usr/bin/php
<?php echo preg_replace('/\n.*/', '', "123\n456\n789") ?>
$ ./test.php
Content-type: text/html
X-Powered-By: PHP/4.3.3

123
$
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top