用于将字符串拆分为数组的正则表达式

时间:2013-08-22 15:48:56

标签: php regex preg-match

我有一个这样的字符串:

== 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 />
    )

我不理解正常的表达,我无法弄清楚如何解决我的问题。

3 个答案:

答案 0 :(得分:1)

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

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

Demo on regex101

答案 1 :(得分: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
)

答案 2 :(得分:0)

在这里,我们使用preg_match_alllook around assertions in RegEx将每个元素分解为自己的数组。

<?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
)