Split all html tags into a array

回眸只為那壹抹淺笑 提交于 2021-02-08 12:09:17

问题


Let's suppose that I have this code below:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>    
<body>
<div id="x">Hello</div>
<p>world</p>
<h1>my name</h1>
</body>
</html>

And I need to extract all html tags and put inside a array, like this:

'0' => '<!DOCTYPE html>',
'1' => '<html>',
'2' => '<head>',
'3' => '<meta charset="UTF-8">',
'4' => '<title>Title of the document</title>',
'5' => '</head>',
'6' => '<body>',
'7' => '<div id="x">Hello</div>',
'8' => '<p>world</p>',
'9' => '<h1>my name</h1>',
....

in my case I have no need to get all the existing content within a tag , for me only catch the beginning of each tag was already very good.

How I can do that?


回答1:


Use the following solution with preg_match_all function:

$html_content = '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>    
<body>
<div id="x">Hello</div>
<p>world</p>
<h1>my name</h1>
</body>
</html>';

preg_match_all("/\<\w[^<>]*?\>([^<>]+?\<\/\w+?\>)?|\<\/\w+?\>/i", $html_content, $matches);
// <!DOCTYPE html> is standardized document type definition and is not a tag

print_r($matches[0]);

The output:

Array
(
    [0] => <html>
    [1] => <head>
    [2] => <meta charset="UTF-8">
    [3] => <title>Title of the document</title>
    [4] => </head>
    [5] => <body>
    [6] => <div id="x">Hello</div>
    [7] => <p>world</p>
    [8] => <h1>my name</h1>
    [9] => </body>
    [10] => </html>
)



回答2:


The best way to go is to load the HTML into a DOMDocument class and iterate through the nodes.

See related question here: https://stackoverflow.com/a/20025973/2870598



来源:https://stackoverflow.com/questions/38542878/split-all-html-tags-into-a-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!