【问题标题】:php preg_split how to split by hrphp preg_split 如何按小时拆分
【发布时间】:2013-04-30 07:32:16
【问题描述】:

我想使用 php preg_split 分割一些文本,例如:

<hr style="text-align: justify;"> or
<hr>  or
<hr style="other style here">

例如文本:"text 1&lt;hr&gt;text 2&lt;hr style="other style here"&gt;text 3 应该给我:

array 
[0] text 1
[1] text 2
[2] text 3

试图找出正则表达式,但对我来说太难了:/

【问题讨论】:

    标签: php preg-split


    【解决方案1】:

    只需搜索&lt;hr,然后搜索直到看到&gt;

    $arr = preg_split('/<hr[^>]*>/', $str);
    

    Demo

    通常我会建议使用 DOM 解析器,但对于这些孤立的情况,正则表达式也能胜任。

    【讨论】:

    • 我很接近...正在做类似的事情:'/
      /' 但它没有用。感谢您的帮助
    • 或者,如果你想将匹配限制为只匹配没有属性的 hr 标签和那些有样式属性的标签,$arr = preg_split('/&lt;hr(?: style=".*")?&gt;/', $str);
    • @eyecatchUp 我不确定在这种情况下这会有什么用:)
    • @Jack 好吧,其实我只是想回答这个问题。但是由于您快了几秒钟并且您的回答更正确,所以我只是将其作为评论。在什么情况下这可能有用?好吧,也许像$str = 'a text that contains "&lt;hr" (for whatever reason) would match until next &gt; occurs&lt;hr&gt;text 2&lt;hr style="other style here"&gt;text 3';这样的刺痛;-)
    猜你喜欢
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多