getting all values from h1 tags using php

2020-01-27 03:12发布

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

Example, if this where the given input string:

<h1>hello</h1>
<p>random text</p>
<h1>title number two!</h1>

I need to receive an array containing this:

titles[0] = 'hello',
titles[1] = 'title number two!'

I already figured out how to get the first h1 value of the string but I need all the values of all the h1 tags in the given string.

I'm currently using this to receive the first tag:

function getTextBetweenTags($string, $tagname) 
 {
  $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
  preg_match($pattern, $string, $matches);
  return $matches[1];
 }

I pass it the string I want to be parsed and as $tagname I put in "h1". I didn't write it myself though, I've been trying to edit the code to do what I want it to but nothing really works.

I was hoping someone could help me out.

Thanks in advance.

标签: php html find
4条回答
我想做一个坏孩纸
2楼-- · 2020-01-27 03:33
 function getTextBetweenH1($string)
 {
    $pattern = "/<h1>(.*?)<\/h1>/";
    preg_match_all($pattern, $string, $matches);
    return ($matches[1]);
 }
查看更多
男人必须洒脱
3楼-- · 2020-01-27 03:34

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();
    }
}
查看更多
欢心
4楼-- · 2020-01-27 03:40

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;
    }
}
查看更多
欢心
5楼-- · 2020-01-27 03:44
function getTextBetweenTags($string, $tagname){
    $d = new DOMDocument();
    $d->loadHTML($string);
    $return = array();
    foreach($d->getElementsByTagName($tagname) as $item){
        $return[] = $item->textContent;
    }
    return $return;
}
查看更多
登录 后发表回答