PHP/regex: How to get the string value of HTML tag?

前端 未结 8 2036
忘了有多久
忘了有多久 2020-11-28 07:24

I need help on regex or preg_match because I am not that experienced yet with regards to those so here is my problem.

I need to get the value \"get me\" but I think

相关标签:
8条回答
  • 2020-11-28 08:17

    Since attribute values may contain a plain > character, try this regular expression:

    $pattern = '/<'.preg_quote($tagname, '/').'(?:[^"'>]*|"[^"]*"|\'[^\']*\')*>(.*?)<\/'.preg_quote($tagname, '/').'>/s';
    

    But regular expressions are not suitable for parsing non-regular languages like HTML. You should better use a parser like SimpleXML or DOMDocument.

    0 讨论(0)
  • 2020-11-28 08:18

    In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W] to match all characters.

    function getTextBetweenTags($string, $tagname) {
        $pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
        preg_match($pattern, $string, $matches);
        return $matches[1];
    }
    
    0 讨论(0)
提交回复
热议问题