preg_match_all text between alteration strings

I would need to get the text between certain strings with preg_match_all. I've tried using alternation, but I'm not getting the right info out. What I need is to get the randomtext between weekday-strings. From Friday it should go to the end of the text.

My data is as follows:

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

What I have now is this, but it only captures the stuff after Monday, when it should stop to Tuesday and then do it again:

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

Any ideas?

Answers


You can use 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>';

Outputs

<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>

Try this,use m modifier and ^+$ to match each line of your text.

$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);

In your example actually the 'Random text....' is not between certain string as it lacks the string at the end, ie after Friday

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)

Need Your Help

Rails - escaping SQL params

sql ruby-on-rails database sql-injection

I am doing some plain SQLs in my rails model (for purists this is just for complex SQLs :)

How to make cron job to run every 15 minutes on Thursday starting at 4pm?

crontab

What would be the line in crontab to run some script every 15 minutes starting at 4pm every Thursday, until the midnight? How to modify it to run until Friday 11am?