Jump to content

Archived

This topic is now archived and is closed to further replies.

denhamd2

Preg match question - urgent help needed

Recommended Posts

Hi,

I have some html stored in a variable $myhtml with a <table> with a few rows. There are currently a lot of rows but I basically just want to echo the first 7 rows, i.e. only take up to the 7th occurance of </tr> ... any ideas on how to do this?

Many thanks in advance...

Share this post


Link to post
Share on other sites
Is the variable always only going to be one table, or could it contain more than one?

Regards
Huggie

Share this post


Link to post
Share on other sites
ok, and do you want complete code returned or just partial code?  I'll explain the question.  Do you want the <table> tag along with the first 7 <tr> tags, or just the 7 <tr> tags, or the <table>, the first 7 <tr> tags and then everything after the last <tr> tag?

Long winded, but hopefully makes sense...

Regards
Huggie

Share this post


Link to post
Share on other sites
ok, give this a try...

[code]<?php
// Maximum number of rows to display
$max = 7;

preg_match_all('|<tr>.*?</tr>|ms', $myhtml, $matches);

for ($i = 0; $i < $max; $i++){
  echo $matches[0][$i];
}
?>[/code]

Regards
Huggie

Share this post


Link to post
Share on other sites
[code]
<pre>
<?php

$html = <<<HTML
<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>4</td></tr>
<tr><td>5</td></tr>
<tr><td>6</td></tr>
<tr><td class="something">7</td></tr>
<tr><td>8</td></tr>
<tr><td>9</td></tr>
<tr><td>10</td></tr>
</table>
HTML;

preg_match_all('%<tr[^>]*>(.*?)</tr>%', $html, $matches);
$first_7 = array_slice($matches[1], 0, 7);
print_r($first_7);

?>
</pre>
[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.