0

There have some texts, how to use php regular get the 2ed and 3rd <div class="partright">? Thanks.

<div class="wrap">
  <div class="content>
    <div class="partleft">
    text1
    </div>
    <div class="partright">
    text2
    </div>
  </div>
  <div class="content>
    <div class="partleft">
    text3
    </div>
    <div class="partright">
    text4
    </div>
  </div>
  <div class="content>
    <div class="partleft">
    text5
    </div>
    <div class="partright">
    text6
    </div>
  </div>
</div>

I want output

<div class="partright">
text4
</div>
<div class="partright">
text6
</div>
Alan Moore
  • 71,299
  • 12
  • 93
  • 154
yuli chika
  • 8,763
  • 20
  • 74
  • 122

3 Answers3

4

Your question is very incomplete but I assume your talking about traversing the elements to modify them in some way.

You should look at the following library called SimpleDOM

And usage would be like:

require_once 'simple_dom.class.php';

$html = "<html_data_here>";
$html = str_get_html($html);

foreach($html->find(".partleft:nth(2),.partleft:nth(3)") as $p)
{
    echo $p->outerText;
}

Note: The above is an example and may not work as expected, for working examples please see the Simple Dom site linked above.

RobertPitt
  • 55,891
  • 21
  • 113
  • 158
1

You can't parse [X]HTML with regex. RegEx match open tags except XHTML self-contained tags use SimpleXML indeed.

Community
  • 1
  • 1
chx
  • 10,915
  • 7
  • 51
  • 118
0

You could build a regular expression that would match

<div class="partright">(.*)</div>

Put all matches in an array and take the 2nd and third element from the array.

gnur
  • 4,612
  • 2
  • 21
  • 33