开发者

Migration from ereg to preg_match: copying a file until a pattern repeated itself X times

开发者 https://www.devze.com 2023-04-13 08:25 出处:网络
I was maintaining some code using ereg, and made the migration to preg_match (not forgetting the delimiter), but it broke my function.

I was maintaining some code using ereg, and made the migration to preg_match (not forgetting the delimiter), but it broke my function.

Here is my original function, which take a file, and create a cropped copy which stopped after lines only composed of # are encountered 6 times:

function createStrippedFile($path1, $path2)
{
    $lines = file($path1);

    $handle = fopen($path2,"w");

    // 6
    $index = 0;

    foreach ($lines as $line)
    {
        $line = trim($line);

        if ($index != 7)
            fwrite($handle,$line."\r\n");

        if (ere开发者_JAVA技巧g("^[#]+$",$line) !== FALSE)
            ++$index;
    }

    fwrite($handle,"END OF DOC\r\n");
    fclose($handle);
}

In this code I changed:

if (ereg("^[#]+$",$line) !== FALSE)

by

if (preg_match('/^[#]+$/',$line) !== FALSE)

but now it isn't cropping anymore. Is there anything I missed when doing the transition?

PS: If someone know of a better way to do what I'm trying to do, he can also write it.


It seems the problem is preg_match returns 0 in case there's no matches, and 0 !== FALSE. I would try to remove this code "!== FALSE" and check if it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号