3

I'm trying to get a string after a delimiter to the end of line with PHP and preg_match. These are my codes:

<?php
$stringa = <<<EOT
var1=Ciao
var2=Variabile
var3=We
EOT;
preg_match("#var2=(.*?)\n#", $stringa, $boh);
print_r($boh);
?>

This works, but not for the last line, if I replace var2 with var3 in the regex the generated array will be empty.

4

4 回答 4

3

使用多行模式,m修饰符,以便$匹配换行符或字符串结尾:

preg_match('#var2=(.*?)$#m', $stringa, $boh);
于 2013-07-24T14:10:43.990 回答
3

使用交替:

#var2=(.*?)(\n|$)#
           ^  ^^^
于 2013-07-24T14:07:58.377 回答
1

原因是您需要在“我们”之后换行才能正确匹配:

<?php
$stringa = <<<EOT
var1=Ciao
var2=Variabile
var3=We

EOT;
preg_match("#var3=(.*?)\n#", $stringa, $boh);
print_r($boh);
?>
于 2013-07-24T14:08:49.847 回答
0

[^\n]您可以使用排除所有换行符而不是使用点:

preg_match('~(?<=var3=)[^\n]+~', $stringa, $boh);
于 2013-07-24T14:26:52.773 回答