regex help with getting tag content in PHP

后端 未结 4 1358
有刺的猬
有刺的猬 2021-01-28 03:47

so I have the code

function getTagContent($string, $tagname) {

    $pattern = \"/<$tagname.*?>(.*)<\\/$tagname>/\";
    preg_match($pattern, $string         


        
4条回答
  •  天命终不由人
    2021-01-28 04:22

    Have your php function getTagContent like this:

    function getTagContent($string, $tagname) {
        $pattern = '/<'.$tagname.'[^>]*>(.*?)<\/'.$tagname.'>/is';
        preg_match($pattern, $string, $matches);
        print_r($matches);
    }
    

    It is important to use non-greedy match all .*? for matching text between start and end of tag and equally important is to use flags s for DOTALL (matches new line as well) and i for ignore case comparison.

提交回复
热议问题