简体   繁体   中英

How can I use Regex in a While Loop in PHP?

I've to do the Regex in a While loop bc its to much data to do it in once. By now I can go throw the Data and the regex also works but the Data get not stored. So How can I do this?

This is my code now:

$handle = @fopen($PathToFile, "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        if (preg_match_all('/^\w+\s+\d+\s('. $SelectedTime .':\d+.\d+).\d+.\d+\s(.+)/im', $buffer, $matches, PREG_SET_ORDER)) {
            $decodeData[] .= $matches;
        }
        else {

        }
    }

var_dump($decodeData);
}
fclose($handle);

For help I would be really glad

This is wrong syntax, it is not a string concatenation.

Instead of

$decodeData[] .= $matches;

Output:

$decodeData[0] = "Result1Result2Result3Result4";

Use

$decodeData[] = $matches;

Output:

$decodeData[0] = "Result1";
$decodeData[1] = "Result2";
$decodeData[2] = "Result3";
$decodeData[3] = "Result4";

You need to use preg_quote function to escape $SelectedTime variable correctly and use $decodedData[] = $matches without .= .

$handle = @fopen($PathToFile, "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        $pattern = '/^\w+\s+\d+\s('. preg_quote($SelectedTime) .':\d+.\d+).\d+.\d+\s(.+)/im';
        if (preg_match_all($pattern, $buffer, $matches, PREG_SET_ORDER)) {
            $decodeData[] = $matches; // just assignment operator
        }
        else {

        }
    }

var_dump($decodeData);
}
fclose($handle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM