Saturday 3 November 2018

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...