Search code examples
phpregexpreg-match

How do I get data from two HTML Divs using preg_match?


I am trying to get data between this two div:

--<div id="p_tab4" class="p_desc" style="display: block;">
--<div id="p_top_cats" class="p_top_cats">

I am using the below regex, but it's not getting me anything:

/<div id=\"p_tab4\" class=\"p_desc\" style=\"display: block;\">(.*?)<div id=\"p_top_cats\" class=\"p_top_cats\">/

How can I correct this regex?


Solution

  • Seems nothing wrong with your regex but you need to turn on the DOTALL mode s, so that the dot in your regex will also matches the newline character (line breaks).

    ~<div id=\"p_tab4\" class=\"p_desc\" style=\"display: block;\">(.*?)<div id=\"p_top_cats\" class=\"p_top_cats\">~s
    

    Code:

    $re = '~<div id=\"p_tab4\" class=\"p_desc\" style=\"display: block;\">(.*?)<div id=\"p_top_cats\" class=\"p_top_cats\">~s';
    $str = "--<div id=\"p_tab4\" class=\"p_desc\" style=\"display: block;\">\n--<div id=\"p_top_cats\" class=\"p_top_cats\">";
    preg_match($re, $str, $matches);
    echo $matches[1];
    

    DEMO