使用 php 从 h1 标签中获取所有值 [英] getting all values from h1 tags using php

查看:20
本文介绍了使用 php 从 h1 标签中获取所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想接收一个包含文本中所有 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;
    }
}

这篇关于使用 php 从 h1 标签中获取所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆