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 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?