Jump to content

Archived

This topic is now archived and is closed to further replies.

kiss-o-matic

Trying to match zero or more occurences

Recommended Posts

Can't figure this one out.

[code]
if ( preg_match("/(flag1.+)*(flag2.+)*/s", $definition, $matches ) ) {

        echo "found " . sizeof($matches) . " matches<br>";

        for ( $i = 1; $i <= sizeof($matches); $i++ ) {
            echo "$i :" . $matches[$i] . "<br>";
        }
} else {
    echo "no match<br>";
}
[/code]

$definition will most of the time look like this:
[code]
flag1
He runs
She runs
They run

flag2
he cries
she cries
they cry
[/code]

Although sometimes it will have text only in the flag1 section, and sometimes only in the flag2 section. So naturally, I want to match zero or more occurences of both of them. I thought the above would work, but alas, it does not.. In fact, it's only reporting one match. O_O Seems if I use one *, I can half of it to work, but of course, I need all of it to.

Share this post


Link to post
Share on other sites
[code]<?php

$definition = <<<DEF
flag1
He runs
She runs
They run

flag2
he cries
she cries
they cry
DEF;

    $initial_data = preg_split(
        '/(flag.+)/',
        $definition,
        -1,
        PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
    );

    echo '<pre>', print_r($initial_data, true), '</pre>';

    $key = '';
    $index = 0;
    foreach ($initial_data as $item) {
        $item = trim($item);
        ### Values
        if (!($index % 2)) {
            $key = $item;
        }
        ### Keys
        else {
            $final_data["$key"] = explode("\n", $item);
        }
        ++$index;
    }

    echo '<pre>', print_r($final_data, true), '</pre>';

?>[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.