使用preg_match_all拆分长字符串时出现问题


Having problems splitting a long string with preg_match_all

我有一个变量(文本),每次更新时都会用句子更新。当我显示这个数组时,它变成了一个长句,为了可读性,我想把它分解成单句。

<?php
$pattern = '~''d+-''d+-''d{4} // ''w+: ~ ';
$subject = '01-02-2015 // john: info text goes here 10-12-2015 // peter: some more info
';
$matches = array();
$result = preg_match_all ($pattern, $subject, $matches);
?>

哪个输出:

$matches:
array (
  0 => 
  array (
    0 => '01-02-2015 // john: ',
    1 => '10-12-2015 // peter: ',
  ),
)

我希望输出为:

$matches:
array (
  0 => 
  array (
    0 => '01-02-2015 // john: info text goes here',
    1 => '10-12-2015 // peter: some more info',
  ),
)

我需要这样的输出,这样我就可以使用foreach循环来打印每个句子。

ps。我想先尝试让它以这种方式工作,因为否则我需要更改数据库中的许多条目。

pps。正如你所看到的,我也不是regex的英雄,所以我希望有人能帮助我!

只需像下面这样更改正则表达式,

$pattern = '~'d+-'d+-'d{4} // 'w+: .*?(?='s'd+|$)~';

.*?将进行零个或多个字符的非贪婪匹配,直到到达后面跟着数字的空格或行的末尾。

演示

$str = "01-02-2015 // john: info text goes here 10-12-2015 // peter: some more info";
preg_match_all('~'d+-'d+-'d{4} // 'w+: .*?(?='s'd+|$)~', $str, $matches);
print_r($matches);

输出:

Array
(
    [0] => Array
        (
            [0] => 01-02-2015 // john: info text goes here
            [1] => 10-12-2015 // peter: some more info
        )
)