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
  • 73,866
  • 12
  • 100
  • 156
yuli chika
  • 9,053
  • 20
  • 75
  • 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
  • 56,863
  • 21
  • 114
  • 161
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
  • 11,270
  • 7
  • 55
  • 129
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,671
  • 2
  • 20
  • 33