douzhang6646 2012-12-04 00:39
浏览 400
已采纳

使用正则表达式替换段落标记

I need to take the output of $one and make an array, however, the regex is not right because all I get back is an array with one key and one value; basically, the entire string. If there are 10 paragraph tags in the string then I should get 10 values in the array.

What is wrong with my regex?

Ideally, what I would like to have in the output array are two arrays, one with the paragraph tags and another with just the text between them.

$one = preg_replace( '/<p>/i', '<p class="test">', $str ); // This gives me what I need
print_r(explode( '/<p class="test">/iU', $one )); // This does not
  • 写回答

1条回答 默认 最新

  • duanquyong8164 2012-12-04 00:54
    关注

    The problem is simple. Explode does not use regex. This should work for you.

    print_r(explode('<p class="test">', $one ));
    

    EDIT: This ought to do what you want.

    $pattern = '/(?P<open><p class="test">)'
              . '(?P<content>.*)'
              . '(?P<close><\/p>)/i';
    preg_match_all($pattern, $one, $matches);
    print_r($matches);
    

    EDIT: Simplified version without the match tags:

    $pattern = '/(<p class="test">)(.*)(<\/p>)/i';
    preg_match_all($pattern, $one, $matches);
    print_r($matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失