getting all values from h1 tags using php

前端 未结 4 1184
灰色年华
灰色年华 2020-11-30 03:43

I want to receive an array that contains all the h1 tag values from a text

Example, if this where the given input string:

hello

相关标签:
4条回答
  • 2020-11-30 04:04
     function getTextBetweenH1($string)
     {
        $pattern = "/<h1>(.*?)<\/h1>/";
        preg_match_all($pattern, $string, $matches);
        return ($matches[1]);
     }
    
    0 讨论(0)
  • 2020-11-30 04:07

    you could use simplehtmldom:

    function getTextBetweenTags($string, $tagname) {
        // Create DOM from string
        $html = str_get_html($string);
    
        $titles = array();
        // Find all tags 
        foreach($html->find($tagname) as $element) {
            $titles[] = $element->plaintext;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:10
    function getTextBetweenTags($string, $tagname){
        $d = new DOMDocument();
        $d->loadHTML($string);
        $return = array();
        foreach($d->getElementsByTagName($tagname) as $item){
            $return[] = $item->textContent;
        }
        return $return;
    }
    
    0 讨论(0)
  • 2020-11-30 04:10

    Alternative to DOM. Use when memory is an issue.

    $html = <<< HTML
    <html>
    <h1>hello<span>world</span></h1>
    <p>random text</p>
    <h1>title number two!</h1>
    </html>
    HTML;
    
    $reader = new XMLReader;
    $reader->xml($html);
    while($reader->read() !== FALSE) {
        if($reader->name === 'h1' && $reader->nodeType === XMLReader::ELEMENT) {
            echo $reader->readString();
        }
    }
    
    0 讨论(0)
提交回复
热议问题