dongtuoji5396 2016-05-12 01:10
浏览 122
已采纳

将HTML字符串转换为PHP数组

Assuming an HTML string like this:

$str = '<p>Hello World!</p><p style="text-align:center"><img src="foo.png" /><br /></p>';

It is possible to convert it into an array like this?

[0] => '<p>Hello World!</p>'
[1] => '<p style="text-align:center">'
[2] => '<img src="foo.png" />'
[3] => '<br />'
[4] => '</p>'

I tried using DOMDocument many different ways but the problem seems to always boil down to parenting. I need to traverse the HTML without regard for parent/child relationships.

  • 写回答

4条回答 默认 最新

  • dongtao9158 2016-05-12 02:04
    关注

    @olibiaz' Answer will do..

    Just wanted to show another way of doing this using preg_split.

    $str = '<p>Hello World!</p><p style="text-align:center"><img src="foo.png" /><br /></p>';
    $flags = PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY;
    $regex = '/(<[a-z0-9=\-:." ^\/]+\/>)|(<[^\/]+>[^<\/]+<\/[a-z0-9]+>)|(<[a-z0-9=\-:." ^\/]+>)/';
    $parts = preg_split( $regex, $str, -1, $flags);
    

    OUTPUT:

    array (size=5)
        0 => string '<p>Hello World!</p>' (length=19)
        1 => string '<p style="text-align:center">' (length=29)
        2 => string '<img src="foo.png" />' (length=21)
        3 => string '<br />' (length=6)
        4 => string '</p>' (length=4)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里