从 ereg 迁移到 preg_match:复制文件直到模式重复 X 次
我正在使用 ereg 维护一些代码,并迁移到 preg_match (不要忘记分隔符),但它破坏了我的功能。
这是我的原始函数,它获取一个文件,并创建一个裁剪后的副本,该副本在遇到仅由 # 组成的行 6 次后停止:
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 (ereg("^[#]+$",$line) !== FALSE)
++$index;
}
fwrite($handle,"END OF DOC\r\n");
fclose($handle);
}
在这段代码中,我更改了:
if (ereg("^[#]+$",$line) !== FALSE)
到目前为止
if (preg_match('/^[#]+$/',$line) !== FALSE)
,它不再裁剪了。进行转换时我错过了什么吗?
PS:如果有人知道更好的方法来完成我想做的事情,他也可以写下来。
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 (ereg("^[#]+$",$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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题似乎是 preg_match 在没有匹配项的情况下返回 0,并且 0 !== FALSE。我会尝试删除此代码“!== FALSE”并检查它是否有效。
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.