因此,我正在使用 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.\"']我被卡住了,因为我没有捕获新行或引号。
1 回答
一只名叫tom的猫
TA贡献1906条经验 获得超3个赞
您可以使用此正则表达式(带有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."
)
- 1 回答
- 0 关注
- 123 浏览
添加回答
举报
0/150
提交
取消
