Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php parse h tag with style

Tags:

php

parsing

I couldn't find anything on parsing this sort of example.

<h3 style="color:red; font-size:24px;">This contest is still open.</h3>

Here is my code, but it doesn't work :( I was to parse this exact H3 tag because there are many tags on the page but they don't have style="color:red; font-size:24px;" so I only want to return content from H3 with style="color:red; font-size:24px;" on them

$html = get_file_content('http://www.website.com/contest.php');
preg_match( '#<h3[^>]*>(.*?)</h3>#i', $html, $match );
echo $match[1];
like image 244
FAFAFOHI Avatar asked Dec 21 '25 07:12

FAFAFOHI


1 Answers

Why don't you use DOMDocument? It was designed for parsing HTML; regex wasn't.

$dom = new DOMDocument();

// Assuming it supports URL, if not, put `file_get_contents()` in there.
$dom->loadHTMLFile('http://www.website.com/contest.php');

foreach( $dom->getElemetsByTagName('h3') as $h3) {
   if ($h3->hasAttribute('style') AND
       $h3->getAttribute('style') == 'color:red; font-size:24px;'
   ) {
      echo $h3->nodeValue;
      break;
   }
}
like image 118
alex Avatar answered Dec 23 '25 19:12

alex