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

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

问题描述

我想接收一个数组,其中包含所有来自文本的h1标签值。例如,如果给定输入字符串:

 < h1> hello< / h1> 
< p>随机文本< / p>
< h1> title number two!< / h1>

我需要收到一个包含这个数组的数组:

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

我已经想出了如何得到字符串的第一个h1值,但是我需要给定字符串中所有h1标签的所有值。 b
$ b

我正在使用它来接收第一个标记:

$ p $ function getTextBetweenTags($字符串,$标记名)
{
$ pattern =/< $ tagname?。*>(。*)< \ / $ tagname> /;
preg_match($ pattern,$ string,$ matches);
return $ matches [1];



$ b $ p
$ b我把它传递给我想要被解析的字符串,在h1中。
我没有自己写,虽然我一直在编辑代码来做我想做的,但没有真正的作品。



我希望有人能帮我一把。



在此先感谢。

解决方案

<你可以使用 simplehtmld

  function getTextBetweenTags($ string,$ tagname){
//从字符串
$ html = str_get_html($ string)创建DOM。

$ titles = array();
//查找所有标签
foreach($ html-> find($ tagname)as $ element){
$ titles [] = $ element-> plaintext;
}
}


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.

解决方案

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

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

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