Search code examples
phphtmlhtml-content-extraction

Use PHP to extract HTML code between special tags into an array


Using the sample code below, I want to extract all code between each <<BEGIN>> and <<END>> tag and append the extracted code to an array for further processing later on.

<?php
$html = '<<BEGIN>><div>Some text goes here...</div><<END>><<BEGIN>><table border="0"><tr><td>Table cell text goes here</td></tr></table><<END>><<BEGIN>><ul><li>My string</li><li>Another string</li></ul><<END>>';
?>

The end result needs to look like this:

Array (
    [0] => '<div>Some text goes here...</div>'
    [1] => '<table border="0"><tr><td>Table cell text goes here</td></tr></table>'
    [2] => '<ul><li>My string</li><li>Another string</li></ul>'
)

Hope this makes sense.

Any assistance would be greatly appreciated. Thanks in advance.


Solution

  • Use pretg_match_all() function to do this.

    <?php
    
        $html = '<<BEGIN>><div>Some text goes here...</div><<END>><<BEGIN>><table border="0"><tr><td>Table cell text goes here</td></tr></table><<END>><<BEGIN>><ul><li>My string</li><li>Another string</li></ul><<END>>';
    
        preg_match_all("/<<BEGIN>>(.*)<<END>>/", $html, $result);
    
        echo '<pre>';
        print_r($result[1]);
        echo '</pre>';
    
    ?>
    

    Show the source code of the page and you will see all you wanted :) (, ...)