PHP preg_match直到双线中断

时间:2012-10-01 05:46:03

标签: php preg-match

我在mysql字段中有这些数据:

First text text text text
 text text text text
 text text text text text text
 text text text text text text

Second text text text text
 text text text text
 text text text text text text
 text text text text text text

我正在尝试从第一个单词到双线休息之前进行匹配。我试过了:

preg_match('/First(.*)\n\n/', $mysqlrow, $m);

这不返回任何行。我还尝试了ms修饰符,它们没有返回正确的字符串。我也尝试了\r\n,它没有返回任何内容。

你是怎么做到的

2 个答案:

答案 0 :(得分:6)

您需要s修饰符,还需要将通配符量词更改为非贪婪:

preg_match('/First(.*?)\n\n/s', $mysqlrow, $m);

s选项会使.通配符与\n匹配,而非贪婪将导致*通配符不会占用所有\n\n它在匹配\n\n之前运行。

您也可以选择匹配\r,以防您在数据库中拥有该内容:

preg_match('/First(.*?)\r?\n\r?\n/s', $mysqlrow, $m);

答案 1 :(得分:2)

这是你需要的另一面旗帜。标记“s”允许点捕获换行符。但它会吃掉你的'\ n'。

您可以尝试:

preg_match('/First(.*?)\n\n/s', $mysqlrow, $m);
跟着?颠倒贪婪的行为。请注意,拆分字符串可以使用split函数完成,这可能更适合您的情况。