如何基于html标签将字符串拆分为数组

时间:2019-04-21 02:32:28

标签: php preg-replace

我有一个带有HTML标签的字符串,我想爆炸成如下所示的数组

我要爆炸的标签是:p, h1, h2, h3, h4, h5, <ul>, <ol>

示例:

$data ="<p> Paragraph 1 </p> <h2>h2 tag 1 </h2> <p> Paragraph 2.</p> <p>Paragraph 3 </p> <ol> <li>pizza</li> <li>burgers</li> <li>salad</li> </ol> <ul> <li> <ul> <li> One </li> <li>Twp </li> <li>Three</li> </ul> </li> </ul> <p> Paragraph 
 5 </p> <p>Paragraph 6:</p> <h4> h4 tag</h4> <h1> h4 tag</h1> <h4> h4 tag</h4>"

我需要以下输出:

$array_tags= [
 0 => <p> Paragraph 1 </p>,
 1 => <h2>h2 tag 1 </h2>,
 2 => <p> Paragraph 2 </p>,
 3 => <p> Paragraph 3 </p>,
 4 => <ol> <li>pizza</li> <li>burgers</li> <li>salad</li> </ol>,
 5 => <p> Paragraph 4 </p>,
 6 => <ul> <li> <ul> <li> One </li> <li>Twp </li> <li>Three</li> </ul> </li> </ul>,
 7 =>  <p> Paragraph 5 </p>,
 8 =>  <p> Paragraph 6 </p>,
 9 =>  <h4> h4 tag</h4>,
 10 => <h1> h1 tag</h1>,
];

有人可以帮忙吗?预先感谢!

1 个答案:

答案 0 :(得分:0)

您应该将字符串分割成数组。

$data ="<p> Paragraph 1 </p> <h2>h2 tag 1 </h2> <p> Paragraph 2.</p> <p>Paragraph 3 </p> <ol> <li>pizza</li> <li>burgers</li> <li>salad</li> </ol> <ul> <li> <ul> <li> One </li> <li>Twp </li> <li>Three</li> </ul> </li> </ul> <p> Paragraph 
 5 </p> <p>Paragraph 6:</p> <h4> h4 tag</h4> <h1> h4 tag</h1> <h4> h4 tag</h4>";

    preg_match_all('/<p>(.*?)<\/p>|<h1>(.*?)<\/h1>|<h2>(.*?)<\/h2>|<h3>(.*?)<\/h3>|<h4>(.*?)<\/h4>|<h5>(.*?)<\/h5>|<ul>(.*)<\/ul>|<ol>(.*?)<\/ol>/', $data, $matches);
    dd($matches[0]);

输出

  array:10 [▼
  0 => "<p> Paragraph 1 </p>"
  1 => "<h2>h2 tag 1 </h2>"
  2 => "<p> Paragraph 2.</p>"
  3 => "<p>Paragraph 3 </p>"
  4 => "<ol> <li>pizza</li> <li>burgers</li> <li>salad</li> </ol>"
  5 => "<ul> <li> <ul> <li> One </li> <li>Twp </li> <li>Three</li> </ul> </li> </ul>"
  6 => "<p>Paragraph 6:</p>"
  7 => "<h4> h4 tag</h4>"
  8 => "<h1> h4 tag</h1>"
  9 => "<h4> h4 tag</h4>"
]