douxu5845 2013-08-22 15:48
浏览 44
已采纳

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

I got a string like this:

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

=== Title 2 ===
other content 

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

=== asd2 ===
fgdfgfdgfdgfdgfdgfdgfdg

I'm trying to parse it into array like this:

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

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

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

I've tried this expession for getting paragraph names:

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

but this expresion isn't working as I want, because it doesn't match the whole paragraph the output is like this and it doesn't get the contents:

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

I have also tried ( nl2br cuz I don't know how to use new line in regex )

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

but the result is something like this:

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

I'm not understanding the regular expresions good and I can't figure out how to solve my problem.

  • 写回答

3条回答 默认 最新

  • dongqiang5932 2013-08-22 16:09
    关注

    You could maybe try this regex?

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

    Demo on regex101.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端