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

2022-01-20 00:00:00 find php html

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

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!'

我已经知道如何获取字符串的第一个 h1 值,但我需要给定字符串中所有 h1 标记的所有值.

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];
 }

我将要解析的字符串传递给它,并作为 $tagname 放入h1".虽然不是我自己写的,我一直在尝试编辑代码来做我想做的事情,但没有任何真正的工作.

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.

提前致谢.

推荐答案

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

相关文章