Jump to content


Retrieving integers using Regex from a website HTML code


  • Please log in to reply
2 replies to this topic

#1 Raex

  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 20 August 2014 - 06:32 AM

Hi, I'm trying to retrieve the integer value between the <span> tag from a HTML source code.


HTML source code: 


This is the php code:

<!DOCTYPE html>

//use curl to get html content
function getHTML($url,$timeout)
       $ch = curl_init($url); // initialize curl with given url
       curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // write the response to a variable
       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirects if any
       curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
       curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
       return @curl_exec($ch);
preg_match("/<span>(.*)<\/span>/i", $html, $match);
$title = $match[1];
echo $title;


Whenever I try to run it, this error will come out: Notice: Undefined offset: 1 in C:\xampp\htdocs\myPHP\index.php on line 19.


How to correct it so that it will display all the integer value within the tag name but without the bracket? Thanks

Edited by Raex, 20 August 2014 - 06:38 AM.

#2 cyberRobot

  • Moderators
  • Much to Learn
  • 2,764 posts

Posted 20 August 2014 - 01:24 PM

Have you considered using PHP's DOMDocument class? You could use the getElementsByTagName method to get the <span> tag(s).

#3 Jacques1

  • Members
  • PipPipPip
  • Turtles all the way down
  • 4,224 posts

Posted 20 August 2014 - 01:35 PM

Your regex searches for span elements which are limited to one line (there are none in the document). Without the s modifier, a dot doesn't match linebreaks. However, when you add this modifier, you'll run into the next bug: Now you get everything from the opening span tag to the very last closing span tag somewhere at the end of the document. You might want to read up on greedy quantifiers and non-greedy quantifiers.


But to be honest, the entire approach is awful. I understand that this is just some quick-and-dirty hack. But simply fetching all span elements without attributes in the hopes that those happen to contain your numbers seems a bit too quick and dirty.


Look at the HTML markup of the page: There's actually a structure. I see one big container with the id “category”, I see main categories with the class “item”, and I see subcategories with the class “sub-item”. Those subcategories contain your numbers within a few other elements. So a smarter approach than the usual regex massacre is indeed to actually parse the markup and let the structure guide you to the data.

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users