使用 PHP 解析时,正则表达式未捕获新行或引号

因此,我正在使用 PHP 尝试将文档分成多个部分。下面是一个示例文本。


Preface The idea for this piece of literature came from the Narcotics Anonymous Fellowship itself.


~~~Preface~~~


Step One


"We admitted we were powerless over our addiction, that our lives had become unmanageable." 


~~~Step One~~~

我需要的是在我需要插入数组的符号之前的任何文本。~~~该数组应该具有符号之间的任何键。~~~我还想确保捕获所有新行和引号。但是,我不是 100% 确定这是可能的。


基本上我使用这些~~~符号作为文本中的中断。该文件长约 96 页。因此,我希望最终能够将结果放入单独的文本文件中,其名称等于数组中的键,值作为所述文本文件中的内容。


例子:



$array = [

    'Preface' => 'Preface The idea for this piece of literature came from the Narcotics Anonymous Fellowship itself.',

    'Step One' => 'Step One\n\"We admitted we were powerless over our addiction, that our lives had become unmanageable.\"'

]

我被卡住了,因为我没有捕获新行或引号。


心有法竹
浏览 124回答 1
1回答

一只名叫tom的猫

您可以使用此正则表达式(带有s标志,以允许.匹配换行符)来提取您想要的部分。它会查找最少量的文本,(.*?)后跟~~~一个部分名称([\w ]+)和~~~.(.*?)~~~([\w ]+)~~~我们用于preg_match_all在文本中查找与此正则表达式的所有匹配项(每个匹配项紧随前一个匹配项开始),然后用于array_combine将部分名称与其文本组合:preg_match_all('/(.*?)~~~([\w ]+)~~~/s', $text, $matches);$parts = array_combine($matches[2], $matches[1]);print_r($parts);输出Array(    [Preface] => Preface The idea for this piece of literature came from the Narcotics Anonymous Fellowship itself.    [Step One] => Step One"We admitted we were powerless over our addiction, that our lives had become unmanageable." )
打开App,查看更多内容
随时随地看视频慕课网APP