Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting all values from h1 tags using php

Tags:

html

find

php

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.

like image 793
Pieter888 Avatar asked Jul 21 '10 12:07

Pieter888


People also ask

What does h1 mean in PHP?

Definition and Usage <h1> defines the most important heading. <h6> defines the least important heading. Note: Only use one <h1> per page - this should represent the main heading/subject for the whole page.

Why would you surround a piece of text with h1 h1 tags?

H1 tags are an important part of SEO. All of the important pages on your site should have H1 tags to draw in the reader and give a clear indication of the content on the page. When you have great H1 tags, especially when you match them to your title tags, it can make a big difference to SEO performance.

What is the ending tag for h1?

It has a start tag <body> and an end tag </body> . The <h1> element defines a heading. The <p> element defines a paragraph.

How do you hide an element in h1?

You can visually hide the <h1> in one of the following ways: Use the . wdn-text-hidden class on the <h1>. This will hide it from visual presentation, but keep it available to AT and bots.


2 Answers

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;
    }
}
like image 95
Sergey Eremin Avatar answered Sep 27 '22 18:09

Sergey Eremin


function getTextBetweenTags($string, $tagname){
    $d = new DOMDocument();
    $d->loadHTML($string);
    $return = array();
    foreach($d->getElementsByTagName($tagname) as $item){
        $return[] = $item->textContent;
    }
    return $return;
}
like image 24
Wrikken Avatar answered Sep 27 '22 18:09

Wrikken