Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP解析时,正则表达式不捕获新行或引号_Php_Arrays_Regex - Fatal编程技术网

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

使用PHP解析时,正则表达式不捕获新行或引号,php,arrays,regex,Php,Arrays,Regex,因此,我正在使用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.

因此,我正在使用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.\"'
]
我被卡住了,因为我没有捕获新行或引号。

您可以使用此正则表达式(带有
s
标志,以允许
匹配新行)提取所需的部分。它查找最小数量的文本
(.*)
,后跟
~~
、节名
([\w]+)
~~

(.*?)~~~([\w ]+)~~~
我们使用在文本中查找与此正则表达式的所有匹配项(每个匹配项在前一个匹配项之后立即开始),然后使用将节名称与其文本相结合:

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." 


)

您真的想在值和键中添加
前言吗?是的。我想在“休息”之前把所有的东西都匹配起来。我不在乎它是什么。“第一步”也是如此。我不在乎它是否在值和键中。在解析之前,我在文档中手动定义了密钥。所以我自己定义了关键点。我会在把所有东西分解成单独的文本文件后手动清理,这应该行得通!我做了一个小测试,它似乎起作用了,我们拭目以待吧P@J.Robinson很高兴听到。如果您对文档有任何控制权,则如果节名中不包含空格,则正则表达式的效率会更高,因为它将限制必须执行的回溯量(在这种情况下,您将只使用
\w+
而不是
[\w]+
)。这仅适用于前两个节。它只做了两部分。请参阅此处的pastebin以获取更大的样本量。。。好像它要碎了@罗宾逊粘贴箱中文本的格式与问题中的格式不匹配。。。根据您的示例数据,我假设该部分的第一个文本与结束语(包含在
~
中的部分)文本匹配。给我一点时间来编辑…对不起。那完全是我的错。我试图基本上不让人们因为一堆文本而陷入困境。显然,我的总结能力无助于回答这个问题。我真的很抱歉。谢谢你的帮助!