PHP技术问题:跳过Babylon格式文件开头特定的20行(含###/;行)
It looks like your code is missing checks for lines starting with ;—that's why those two lines aren't being skipped! Your current logic only handles lines starting with #, so the ;-prefixed lines slip through without triggering the continue statement.
Here are two approaches to fix this, depending on your exact needs:
Option 1: Skip Exactly the First 20 Lines
If you know you always need to skip the first 20 lines (regardless of their content), this is the most straightforward solution:
elseif($sourceformat == "Babylon") { // Skip the first 20 lines explicitly for ($skipCount = 0; $skipCount < 20; $skipCount++) { fgets($source_file); } // Now process the rest of the file while (($line = fgets($source_file)) !== false) { $source = trim($line); // ... your existing processing logic here } }
Option 2: Skip All Leading Comment Lines (### or ;)
If the number of leading comment lines might vary, but you want to skip any line that starts with ### or ; at the top of the file, use this approach:
elseif($sourceformat == "Babylon") { while (($line = fgets($source_file)) !== false) { $trimmedLine = trim($line); // Skip lines that start with ### or ; if (strpos($trimmedLine, '###') === 0 || strpos($trimmedLine, ';') === 0) { continue; } // Found the first non-comment line—process it and continue $source = trim($line); // ... your existing processing logic here // If you need to keep processing subsequent lines, remove this break break; } }
Why Your Original Code Failed
Your original checks only looked for lines starting with #, but the two problematic lines start with ;—those weren't covered by any of your conditions. The adjusted code adds the missing check for ; and trims the line first to handle any accidental leading whitespace that might throw off the start-of-line check.
内容的提问来源于stack exchange,提问作者cheeseus

