Jump to content


Photo

Trying to match zero or more occurences


  • Please log in to reply
1 reply to this topic

#1 kiss-o-matic

kiss-o-matic
  • Members
  • PipPipPip
  • Advanced Member
  • 51 posts

Posted 18 June 2006 - 06:27 AM

Can't figure this one out.

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>";
}

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

flag2
he cries
she cries
they cry

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.

#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 19 June 2006 - 03:25 PM

<?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>';

?>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users