0

我需要使用 preg_match_all 获取某些字符串之间的文本。我试过使用交替,但我没有得到正确的信息。我需要的是获取工作日字符串之间的随机文本。从星期五开始,它应该到正文的结尾。

我的数据如下:

Monday 1.1.
randomtext
randomtext
Tuesday 2.1.
randomtext
randomtext
Wednesday 3.1
randomtext
randomtext
Thusday 4.1.
randomtext
randomtext
randomtext
Friday 5.1
randomtext
randomtext

我现在拥有的是这个,但它只在星期一之后捕获这些东西,它应该停止到星期二然后再做一次:

/(Monday|Tuesday|Wednesday|Thursday|Friday)([\s\S]+)/

有任何想法吗?

4

3 回答 3

0

试试这个,使用m修饰符和^+$来匹配文本的每一行。

$datas = <<<data
Monday 1.1.
randomtext
randomtext
Tuesday 2.1.
randomtext
randomtext
Wednesday 3.1
randomtext
randomtext
Thusday 4.1.
randomtext
randomtext
randomtext
Friday 5.1
randomtext
randomtext
data;
preg_match_all('#^(?!Monday|Tuesday|Wednesday|Thusday|Friday)\w+$#im',$datas,$matches);
print_r($matches);
于 2012-07-17T11:49:17.670 回答
0

您可以使用preg_split().

$day_pattern = '/([a-z]+?day [\d\.]+\n)/i';
$bits = preg_split(
    $day_pattern,
    $str,
    null,
    PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
if ($bits)
    foreach($bits as $bit)
        echo preg_match($day_pattern, $bit)
            ?
            '<h3>'.$bit.'</h3>'
            :
            '<p>'.$bit.'</p>';

输出

<h3>Monday 1.1.</h3>
<p>randomtext
randomtext</p>
<h3>Tuesday 2.1.</h3>
<p>randomtext
randomtext</p>
<h3>Wednesday 3.1</h3>
<p>randomtext
randomtext</p>
<h3>Thusday 4.1.</h3>
<p>randomtext
randomtext
randomtext</p>
<h3>Friday 5.1</h3>
<p>randomtext
randomtext</p>
于 2012-07-17T12:01:40.213 回答
0

在您的示例中,实际上“随机文本....”不在某些字符串之间,因为它在末尾缺少字符串,即在星期五之后

Monday 1.1.
randomtext1
randomtext2
Tuesday 2.1.
randomtext3
randomtext4
Wednesday 3.1
randomtext5
randomtext6
Thursday 4.1.
randomtext7
randomtext8
randomtext9
Friday 5.1
randomtext10
randomtext11
Monday

If the text will be like above, ie it will be between Weekday string always, you can use the following pattern.

 (?<=Monday|Tuesday|Wednesday|Thursday|Friday)([\s\S]+?)(?=Monday|Tuesday|Wednesday|Thursday|Friday)
于 2012-07-17T12:47:51.633 回答