使用 php 从 h1 标签获取所有值

2022-08-30 23:51:26

我想接收一个数组,其中包含文本中的所有h1标签值

示例,如果这是给定的输入字符串:

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

我需要接收一个包含以下内容的数组:

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

我已经弄清楚了如何获取字符串的第一个h1值,但我需要给定字符串中所有h1标签的所有值。

我目前正在使用它来接收第一个标签:

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

我传递给它我想要被解析的字符串,$tagname我放入“h1”。虽然我不是自己写的,但我一直在尝试编辑代码以做我想做的事情,但没有什么真正起作用。

我希望有人能帮助我。

提前致谢。


答案 1

你可以使用 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;
    }
}

答案 2
function getTextBetweenTags($string, $tagname){
    $d = new DOMDocument();
    $d->loadHTML($string);
    $return = array();
    foreach($d->getElementsByTagName($tagname) as $item){
        $return[] = $item->textContent;
    }
    return $return;
}

推荐