Jump to content


Photo

Preg_Match


  • Please log in to reply
2 replies to this topic

#1 Lytheum

Lytheum
  • Members
  • PipPipPip
  • Advanced Member
  • 79 posts

Posted 04 June 2006 - 05:44 AM

I need helping using this function to find some numbers out of a string of html. The html is the following:

<div class="mainscroll-content"><table cellpadding="3" cellspacing="0" border=0>
<tr>

<td align="left"><a href="overall.ws?table=0&user=zezima">Overall</a></td> 
<td align="right">2</td> 
<td align="right">2164</td> 
<td align="right">554,475,897</td>

</tr></table></div>

Now, I need to find out what is between the first <td></td>, 2nd, 3rd, and fourth - all dynamically (I don't know the numbers yet, this is an example.

This is how I have started it:

preg_match_all ("/<div class=\"mainscroll-content\">([^`]*?)<\/div>/", $data, $matches);

// Loop through each content item
foreach ($matches[0] as $match) {
    // Stat
    preg_match ("/<a href=\"overall.ws?table=0&user= . $user\">([^`]*?)<\/a><\/td>", $match, $temp);
    $stat = $temp['1'];
    $stat = strip_tags($stat);
    $stat = trim($stat);
    // Rank
    preg_match ("/<td align=\"right\">([^`]*?)<\/td>/", $match, $temp);
    $rank = $temp['1'];
    $rank = trim($rank);
   // Level
    preg_match ("/<td align=\"right\">([^`]*?)<\/td>/", $match, $temp);
    $level= $temp['1'];
    $level = trim($level);
   // Exp
    preg_match ("/<td align=\"right\">([^`]*?)<\/td>/", $match, $temp);
    $exp = $temp['1'];
    $exp = trim($exp);

It works..almost. It finds what is between the first <td></td>. for each different one I called. So it all finds the same data (duh).

Sorry for the long code, and if I explained it wrong I will retry tomorrow (1am).

#2 poirot

poirot
  • Members
  • PipPipPip
  • Advanced Member
  • 646 posts
  • LocationAustin, TX

Posted 04 June 2006 - 06:11 AM

Changed your regular expression, and now using preg_match_all:

<?php

$str = '<td align="left"><a href="overall.ws?table=0&user=zezima">Overall</a></td>
<td align="right">2</td>
<td align="right">2164</td>
<td align="right">554,475,897</td>';

$pattern = '/<td(?:[^>])*>(.*?)<\/td>/s';
preg_match_all($pattern, $str, $m);

$temp = array_map('trim', $m[1]);

echo '<pre>';
print_r($temp);
echo '</pre>';

?>

Which outputs

Array
(
    [0] => <a href="overall.ws?table=0&user=zezima">Overall</a>
    [1] => 2
    [2] => 2164
    [3] => 554,475,897
)

~ D Kuang

#3 Lytheum

Lytheum
  • Members
  • PipPipPip
  • Advanced Member
  • 79 posts

Posted 04 June 2006 - 01:32 PM

Thanks so much. Exactly what I needed.

-solved-




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users