Check tag & get the value inside tag using PHP

后端 未结 2 1087
我在风中等你
我在风中等你 2021-01-29 11:24

I\'ve been confused. So here\'s my problem, I have a text like this :

Head of Pekalongan Regency, Dra. Hj.. Siti Qomariy         


        
相关标签:
2条回答
  • 2021-01-29 11:48

    Did you try the strip_tags() function?

    <?php
    
        $s = "<ORGANIZATION>Head of Pekalongan Regency</ORGANIZATION>, Dra. Hj.. Siti Qomariyah , MA and her staff were greeted by <ORGANIZATION>Rector of IPB</ORGANIZATION> Prof. Dr. Ir. H. Herry Suhardiyanto , M.Sc. and <ORGANIZATION>officials of IPB</ORGANIZATION> in the guest room.";
    
        $r = strip_tags($s);
    
        var_dump($r);
    
    ?>
    

    demo

    0 讨论(0)
  • 2021-01-29 11:58

    preg_match will only return the first match, and your current code will fail if:

    • The tag is not uppercased in the same way
    • The tag's contents are on more than one line
    • There are more than one of the tag on the same line.

    Instead, try this:

    function get_text_between_tags($string, $tagname) {
        $pattern = "/<$tagname\b[^>]*>(.*?)<\/$tagname>/is";
        preg_match_all($pattern, $string, $matches);
        if(!empty($matches[1]))
            return $matches[1];
        return array();
    }
    

    This is acceptable use of regexes for parsing, because it is a clearly-defined case. Note however that it will fail if, for whatever reason, there is a > inside an attribute value of the tag.

    If you prefer to avoid the wrath of the pony, try this:

    function get_text_between_tags($string, $tagname) {
        $dom = new DOMDocument();
        $dom->loadHTML($string);
        $tags = $dom->getElementsByTagName($tagname);
        $out = array();
        $length = $tags->length;
        for( $i=0; $i<$length; $i++) $out[] = $tags->item($i)->nodeValue;
        return $out;
    }
    
    0 讨论(0)
提交回复
热议问题