如何使用preg_match从某个div获取数据?

时间:2012-01-12 10:36:34

标签: php regex preg-match

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

我想让PHP在这个特定的DIV中找到信息

我尝试过很多preg_match函数,但我不理解REGEX。

HELP?

2 个答案:

答案 0 :(得分:1)

试试这个:

<?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>";

答案 1 :(得分:1)

<?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);
?>

尝试使用此匹配所有div元素