0

我有一个这样的字符串:

== Paragraph == 
=== title 1 ===
content

=== Title 2 ===
other content 

== Paragraph 2 ==
=== asd1 ===
dfdsfdsfdsfdsfdsfsdfdsf

=== asd2 ===
fgdfgfdgfdgfdgfdgfdgfdg

我试图将它解析成这样的数组:

$arr = array( 
    array("title"=>"Paragraph", "content" => "=== title 1 ===
content

=== Title 2 ===
other content "),
array("title"=>"Paragraph 2", "content" => "=== asd1 ===
dfdsfdsfdsfdsfdsfsdfdsf

=== asd2 ===
fgdfgfdgfdgfdgfdgfdgfdg"));

我已经尝试过这个表达式来获取段落名称:

preg_match_all("@== (.*?) ==.*?@is", $data, $paragraphs);

但是这个表达式没有按我的意愿工作,因为它与整个段落不匹配输出是这样的并且它没有得到内容:

Array
    (
        [0] => Paragraph
        [1] => title 1
        [2] => Title 2
        [3] => Paragraph 2
        [4] => asd1
        [5] => asd2
    )

我也试过(nl2br 因为我不知道如何在正则表达式中使用新行)

$data = nl2br($data);
preg_match_all("@== (.*?) ==<br />.*?@is", $data, $paragraphs);

但结果是这样的:

[0] => Array
    (
        [0] => == Paragraph == <br />
=== title 1 ===<br />
content<br />
<br />
 === Title 2 ===<br />
 other content <br />
 <br />
 == Paragraph 2 ==<br />
    )

我不理解正则表达式,我不知道如何解决我的问题。

4

3 回答 3

1

你也许可以试试这个正则表达式?

@(==[^=]+==)(.+?(?=[^=]==[^=]|$))@s

正则表达式 101 上的演示

于 2013-08-22T16:09:52.803 回答
0

怎么样:

$str = '== Paragraph == 
=== title 1 ===
content

=== Title 2 ===
other content 

== Paragraph 2 ==
=== asd1 ===
dfdsfdsfdsfdsfdsfsdfdsf

=== asd2 ===
fgdfgfdgfdgfdgfdgfdgfdg';
$list = preg_split('/(?<!=)== (.+?) ==(?!=)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($list);

输出:

Array
(
    [0] =>
    [1] => Paragraph
    [2] =>
=== title 1 ===
content

=== Title 2 ===
other content


    [3] => Paragraph 2
    [4] =>
=== asd1 ===
dfdsfdsfdsfdsfdsfsdfdsf

=== asd2 ===
fgdfgfdgfdgfdgfdgfdgfdg
)
于 2013-08-22T17:50:30.300 回答
0

在这里,我们使用RegEx 中的断言preg_match_all将每个元素分解成它自己的数组片段。

<?php

    $pattern = "~((?<!=)(?<=={2})\s*((?<=\s)[^=]+(?=\s))\s*(?=={2})(?!=)|(?<====)\s*((?<=\s)[^=]+(?=\s))\s*(?====)|(?<==\s)\s*((?<=\s)[^=]+)\s*(?!=))~";

    $string="== Paragraph == 
    === title 1 ===
    content

    === Title 2 ===
    other content 

    == Paragraph 2 ==
    === asd1 ===
    dfdsfdsfdsfdsfdsfsdfdsf

    === asd2 ===
    fgdfgfdgfdgfdgfdgfdgfdg";

    preg_match_all($pattern,$string,$matches);


    print_r($matches[0]);


?>

输出

Array
(
    [0] => Paragraph
    [1] =>  title 1 
    [2] => 
content


    [3] =>  Title 2 
    [4] => other content 

    [5] => Paragraph 2
    [6] =>  asd1 
    [7] => 
dfdsfdsfdsfdsfdsfsdfdsf


    [8] =>  asd2 
    [9] => fgdfgfdgfdgfdgfdgfdgfdg
)
于 2013-08-22T19:50:41.187 回答