Jump to content

Trying to match zero or more occurences


kiss-o-matic

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.
Link to comment
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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.