Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

PHP - How to extract content from a div via Regex

I have a string of HTML where some inherited div present and I need to extract only the top level div, for example-

$html= '<div class="test">
            <div>
                <div>Some text 1</div> 
                <div>Image content 2</div>
            </div>
            <div>
                <div>Some text 2</div> 
                <div>Image content 2</div>
            </div>
            ....
        </div>';
$regex ='/<divsclass=["']test["']>.*?</div>/is';
preg_match($regex, $html, $matches);    

But the real problem is the result shows me only the first Some text 1</div>, Please help me to figure out where I made the mistakes?

I need to grab the entire class test 'div' as a result matches.

<div>
    <div>Some text 1</div> 
    <div>Image content 2</div>
</div>
<div>
     <div>Some text 2</div> 
     <div>Image content 2</div>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following regex should do it :

(?s)(?<=<divsclass="test">
).*(?=</div>)

see demo / explanation

PHP

<?php
$regex = '/(?s)(?<=<divsclass="test">
).*(?=</div>)/';
$str = '<div class="test">
            <div>
                <div>Some text 1</div>
                <div>Image content 2</div>
            </div>
            <div>
                <div>Some text 2</div>
                <div>Image content 2</div>
            </div>
            ....
        </div>';
preg_match($regex, $str, $matches);
print_r($matches);
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...