Preg match text in php between html tags

前端 未结 3 565
抹茶落季
抹茶落季 2020-11-29 06:22

Hello I would like to use preg_match in PHP to parse the \"Desired text\" out of the following from a html document

Desired text &

相关标签:
3条回答
  • 2020-11-29 06:22

    What if the string you're matching has multiple lines and is:

    <p class="review"> Desired text1 </p>
    <p class="review"> Desired text2 </p>
    <p class="review"> Desired text3 </p>
    

    That pattern would match once, and the match would be everything in the string.

    I think a better pattern is:

    "'<p class=\"review\">([^<]*)</p>'si"
    
    0 讨论(0)
  • 2020-11-29 06:43

    if you want to return multiple matches then need to use preg_match_all(). You then loop through the second result group ($match[1]) to get just the content between tags.

    $source = "<p class=\"review\"> Desired text1 </p>".
    "<p class=\"review\"> Desired text2 </p>".
    "<p class=\"review\"> Desired text3 </p>";
    
    
        preg_match_all("'<p class=\"review\">(.*?)</p>'si", $source, $match);
    
        foreach($match[1] as $val)
        {
            echo $val."<br>";
    
    
        }
    
    Outputs:
    
    Desired text1
    Desired text2
    Desired text3 
    
    0 讨论(0)
  • 2020-11-29 06:45
    preg_match("'<p class=\"review\">(.*?)</p>'si", $source, $match);
    if($match) echo "result=".$match[1];
    
    0 讨论(0)
提交回复
热议问题