Thursday 25 May 2017

html - getting all values from h1 tags using 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:



hello


random text


title number two!




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.


Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...