jjzjj

PHP:跳过/删除以###开头的行

coder 2024-04-15 原文

我需要能够跳过以 ### 开头的文件的前 20 行。 (实际上有 18 行以### 开头,两行以 ; 开头)。

我尝试过的所有方法都无法跳过相同的两行——我不知道为什么。

这是我尝试过的(这只是我代码的相关部分):

elseif($sourceformat == "Babylon") {

    $line = fgets($source_file);
    if($line[0] === '#') {
        continue;
    }
    if(strpos(trim($line), '#') === 0) {
        continue;
    }
    if(substr($line, 0, 1) == "#") {
        continue;
    }

    $source = trim(fgets($source_file));

    if(empty($source)) {
        continue;
    }

    $target = trim(fgets($source_file));
}
// then I proceed to writing the extracted terms into a new file that has a different format.

我已经单独和一起尝试了上述三种方法($line[0] === '#'strpos(trim($line), '#') substr($line, 0, 1) == '#') – 但同一行总是被跳过(未检测到)。这是整个标题部分的样子(这是 Babylon 词汇表文件的标题(.gls – 但纯文本)。

### Glossary title:Cheeseus Muzik
### Author:Cheeseus
### Description:English - Bulgarian and Bulgarian - English glossary of musical terms
### Source language:Bulgarian
### Source alphabet:Cyrillic
### Target language:Bulgarian
### Target alphabet:Cyrillic
### Icon:
### Browsing enabled?Yes
### Type of glossary:00000000
### Case sensitive words?0
; DO NOT EDIT THE NEXT **SIX** LINES  - Babylon-Builder generated text !!!!!!
### Glossary id:0265922f91878d6e846e9c869d8a89447c6e719e8585886b8692955f91887a9b8474859a85616a279a929ca07f6881507056895d6881304b5142515f42ba6c992e2b23828188719469656840908429504d595b486965418931312d5b47ad7843525650833a233a47514270695543449f31373b7179484e435a8c428827
### Confirmation string:8A148GOK
### File build number:0121DA07
### Build:80"0)2"0
### Glossary settings:00000000
### Gls type:00000001
; DO NOT EDIT THE PREVIOUS **SIX** LINES  - Babylon-Builder generated text !!!!!!

### Glossary section:

a piacere
а пиачере, по желание

a tempo
а темпо, завръщане към основното темпо след отклонение

ad libitum
ат либитум, свободно, по желание

adagio
адажио (бавно)

allargando
аларгандо, забавяне

allegretto
алегрето, весело, бързичко

allegro
алегро, бързо, весело

allentando
алентандо, със забавяне

... (this is the actual glossary – source term on one line, target term on the next, followed by an empty line, then again source term, target term, new line. I only want these lines, while discarding (omitting, removing) the glossary header lines above. The code I have successfully removes all lines starting with # but this one below (the glossary ID), and it also removes the two lines starting with a semi-colon.

这是我似乎无法摆脱的行:

### Glossary id:0265922f91878d6e846e9c869d8a89447c6e719e8585886b8692955f91887a9b8474859a85616a279a929ca07f6881507056895d6881304b5142515f42ba6c992e2b23828188719469656840908429504d595b486965418931312d5b47ad7843525650833a233a47514270695543449f31373b7179484e435a8c428827

我怀疑这是因为这一行很长(或者可能是因为前一行以分号开头?)。我试过指定最大值。 fgets 中读取的每一行的字节长度:

$line = fgets($source_file, 8192);

但这也不起作用。希望你能帮上忙。

整个代码太长,无法放在这里,但它已经可以正常工作了——除了去掉这一行。

解决方案(基于@Mehdi Bounya 的回答)

看来我没有在正确的地方执行我已经完成的检查。这是完全满足我需要的代码:

elseif($sourceformat == "Babylon") {

    if($targetformat == "Wordfast") {
        $converted_source_target_delimiter = "\t";
        $converted_term_delimiter = "\r\n";
    }

    $source = trim(fgets($source_file));

    if(empty($source)) {
        continue;
    }
    if($source[0] === '#') {
        continue;
    }
    if($source[0] === ';') {
        continue;
    }

    $target = trim(fgets($source_file));
}
$exported_entry = $source.$converted_source_target_delimiter.$target.$converted_term_delimiter;

感谢所有提供帮助的人!

最佳答案

您可以使用 fopen 打开文件并遍历各行,然后简单地检查该行是否以您想要的字符开头。

这个函数有两个参数,$file 是文件路径,$startWith 是要跳过的字符数组:

function skipLines($file, $startWith = NULL){
    $handle = fopen($file, "r");
    if ($handle) {
        while (($buffer = fgets($handle)) !== false) {
            if(in_array($buffer[0], $startWith)){
                // Your code if line starts with $startWith
            } else {
                // Your code if line does not start with $startWith
                echo $buffer;
            }
        }
        fclose($handle);
    }
}

skipLines("sample.txt", ['#']); // Result 1


skipLines("sample.txt", [';']); // Result 2


skipLines("sample.txt", ['#', ';']); // Result 3

结果 1:

; DO NOT EDIT THE NEXT **SIX** LINES  - Babylon-Builder generated text !!!!!!
; DO NOT EDIT THE PREVIOUS **SIX** LINES  - Babylon-Builder generated text !!!!!!

结果 2:

### Glossary title:Cheeseus Muzik
### Author:Cheeseus
### Description:English - Bulgarian and Bulgarian - English glossary of musical terms
### Source language:Bulgarian
### Source alphabet:Cyrillic
### Target language:Bulgarian
### Target alphabet:Cyrillic
### Icon:
### Browsing enabled?Yes
### Type of glossary:00000000
### Case sensitive words?0
### Glossary id:0265922f91878d6e846e9c869d8a89447c6e719e8585886b8692955f91887a9b8474859a85616a279a929ca07f6881507056895d6881304b5142515f42ba6c992e2b23828188719469656840908429504d595b486965418931312d5b47ad7843525650833a233a47514270695543449f31373b7179484e435a8c428827
### Confirmation string:8A148GOK
### File build number:0121DA07
### Build:80"0)2"0
### Glossary settings:00000000
### Gls type:00000001

### Glossary section:

结果 3:

// Nothing...

关于PHP:跳过/删除以###开头的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806265/

有关PHP:跳过/删除以###开头的行的更多相关文章

  1. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  2. Ruby - 如何在读取文件时跳过/忽略特定行? - 2

    在读取/解析文件(使用Ruby)时忽略某些行的最佳方法是什么?我正在尝试仅解析Cucumber.feature文件中的场景,并希望跳过不以Scenario/Given/When/Then/And/But开头的行。下面的代码有效,但它很荒谬,所以我正在寻找一个聪明的解决方案:)File.open(file).each_linedo|line|line.chomp!nextifline.empty?nextifline.include?"#"nextifline.include?"Feature"nextifline.include?"Inorder"nextifline.include?

  3. ruby - 如何跳过 CSV 文件的第一行并将第二行作为标题 - 2

    有没有办法跳过CSV文件的第一行,让第二行作为标题?我有一个CSV文件,第一行是日期,第二行是标题,所以我需要能够在遍历它时跳过第一行。我尝试使用slice但它会将CSV转换为数组,我真的很想将其读取为CSV,以便我可以利用header。 最佳答案 根据您的数据,您可以使用另一种方法和skip_lines-option此示例跳过所有以#开头的行require'csv'CSV.parse(DATA.read,:col_sep=>';',:headers=>true,:skip_lines=>/^#/#Markcomments!)do|

  4. ruby - 确定字符串的结尾是否与单独的字符串的开头重叠 - 2

    我想查找字符串的结尾是否与单独字符串的开头重叠。例如,如果我有这两个字符串:string_1='Peoplesaynothingisimpossible,butI'string_2='butIdonothingeveryday.'如何找到string_1末尾的“butI”部分与string_2开头相同?我可以编写一个方法来遍历这两个字符串,但我希望得到一个包含我错过的Ruby字符串方法或Ruby习惯用法的答案。 最佳答案 将MARKER设置为一些从未出现在您的string_1和string_2中的字符串。有一些方法可以动态地做到这一

  5. ruby - Sinatra 不以 twitter gem 开头 - 2

    当我尝试启动sinatra时,出现以下错误/var/lib/gems/1.9.1/gems/sinatra-1.4.4/lib/sinatra/base.rb:1488:instart_server':undefinedmethodrun'forHTTP:模块(NoMethodError)require'sinatra/base'require_relative"twt.rb"classSinatraApp在“twt.rb”中我需要Twitter(5.7.1)require'twitter'classTwitattr_accessor:clientdefinitialize(consu

  6. ruby-on-rails - 是否可以让 ActiveRecord 为使用 :joins option? 加载的行创建对象 - 2

    我需要做这样的事情classUser'User',:foreign_key=>'abuser_id'belongs_to:gameendclassGame['JOINabuse_reportsONusers.id=abuse_reports.abuser_id','JOINgamesONgames.id=abuse_reports.game_id'],:group=>'users.id',:select=>'users.*,count(distinctgames.id)ASgame_count,count(abuse_reports.id)asabuse_report_count',:

  7. ruby - 在 Ruby 中跳过额外的关键字参数 - 2

    我定义了一个方法:defmethod(one:1,two:2)[one,two]end当我这样调用它时:methodone:'one',three:'three'我得到:ArgumentError:unknownkeyword:three我不想从散列中一个一个地提取所需的键或排除额外的键。除了像这样定义方法之外,有没有办法规避这种行为:defmethod(one:1,two:2,**other)[one,two,other]end 最佳答案 如果不想写**other中的other,可以省略。defmethod(one:1,two:2

  8. ruby - 为什么我不能将一个 fixnum 除以另一个 fixnum? - 2

    我目前正在尝试将包含数字82,000的散列counts["email"]除以包含值130万的变量total。当我运行putscounts["email"]/total时,我得到0。为什么我不能对这些进行除法? 最佳答案 您正在执行除法,尽管不是您预期的那样。在Ruby中有许多不同的整数除法:#Integerdivision:5/4#=>1#Floatingpointdivision:5.fdiv(4)#=>1.25#Rationaldivision:5.quo(4)#=>Rational(5,4)您还可以将其中一个整数转换为Floa

  9. ruby - 使用正则表达式检查字符串是否以辅音开头 - 2

    有没有更好的方法在Ruby中编写以下正则表达式?第一个正则表达式匹配以(小写)辅音开头的字符串,第二个以元音字母开头。我正在尝试找出是否有一种方法可以编写与第二个表达式的否定匹配的正则表达式,而不是编写具有多个范围的第一个表达式。string=~/\A[b-df-hj-np-tv-z]/string=~/\A[aeiou]/ 最佳答案 声明$string=~/\A[^aeiou]/将测试字符串是否以非元音字符开头,其中包括数字、标点符号、空格和控制字符。如果您事先知道字符串以字母开头,那很好,但是要检查它是否以辅音开头,您可以使用前

  10. ruby-on-rails - 这个 C 和 PHP 程序员如何学习 Ruby 和 Rails? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我来自C、php和bash背景,很容易学习,因为它们都有相同的C结构,我可以将其与我已经知道的联系起来。然后2年前我学了Python并且学得很好,Python对我来说比Ruby更容易学。然后从去年开始,我一直在尝试学习Ruby,然后是Rails,我承认,直到现在我还是学不会,讽刺的是那些打着简单易学的烙印,但是对于我这样一个老练的程序员来说,我只是无法将它

随机推荐