Jerett Woyciehouski
Jerett Woyciehouski

Reputation: 3

How to get data from a certain div with preg_match?

Example: <div style="font-size:15px;">first matched here</div>

I want to have PHP find the information in this particular DIV

i have tried many preg_match functions but i do not understand the REGEX.

HELP?

Upvotes: 0

Views: 8194

Answers (2)

Augustin stack
Augustin stack

Reputation: 82

<?php
$data = 'aaa <div class="main">content</div> bbb';
preg_match_all ("/<div.*?>([^`]*?)<\/div>/", $data, $matches);
//testing the array $matches
//$matches is an array contains all the matched div elements and its contents
//print_r($matches);
?>

Try this for matching all the div elements

Upvotes: 1

davogotland
davogotland

Reputation: 2777

try this out:

<?php
    //the string to search in
    $s = "<div style=\"font-size:15px;\">first matched here</div>";
    //set up an empty array to facilitate the results
    $matches = array();
    //match with regex
    //pattern has to start and end with the same character (of your choice)
    //here it's #
    //start criteria is an opening div <div> that may contain some text
    //between v and >, so use .*?
    //the dot means "any character", the *? means "any number, but as few as possible"
    //then, define the part to capture. this is done with paranthesis
    //define what to capture. this would be any character, and as few as possible
    //and finally end criteria </div>
    //matches are stored in the out parameter $matches
    preg_match("#<div.*?>(.*?)</div>#", $s, $matches);
    echo "<pre>";
    print_r($matches);
    echo "</pre>";

Upvotes: 1

Related Questions