Reputation: 9221
<?php
require_once("simple_html_dom.php");
$str = '<div class="content"><span>text1</span><span>text2</span><span>text3</span><span>text4</span><span>text5</span><span>text6</span><span>text7</span><span>text8</span><span>text9</span><span>text10</span><span>text11</span><span>text12</span><span>text13</span><span>text14</span><span>text15</span><span>text16</span></div>';
$dom = html_entity_decode($str);
$html = str_get_html($dom);
foreach($html->find('span') as $e)
echo $e . '<br>';
?>
In this code, it can echo every span in one line. But how do I write it so that 3 results will combine in one foreach?
I need a result like:
text1 text2 text3 <br />
text4 text5 text6 <br />
text7 text8 text9 <br />
text10 text11 text12 <br />
text13 text14 text15 <br />
text16
Upvotes: 1
Views: 325
Reputation: 11360
Use the modulus operator %
in your foreach loop.
$counter = 1;
foreach ($html->find('span') as $e) {
echo $e;
if ( ($counter % 3) == 0 ){
echo '<br />';
}
++$counter;
}
Upvotes: 5
Reputation: 16934
You can set an integer and use mod to obtain the remainder.
$i = 1;
foreach($html->find('span') as $e)
{
echo $e;
if (($i % 3) == 0) echo '<br />';
$i++;
}
Upvotes: 2
Reputation: 7600
One way is to have a seperat variable to keep the number per line.
Then that number reaches 3 you break the line with either a
or and start a new one resetting the variable.
Upvotes: 0