A
A
artem782017-05-05 20:59:35
PHP
artem78, 2017-05-05 20:59:35

How to get penultimate element in PHPQuery?

The question is simple - how to get an element by number from the end in phpquery?

<?php
  $html = <<<EOD
<div style="text-align: center;" class="navigation">
        <span class="pagination">
          <span>« novější</span> | 
          <span>1</span> | 
          <a href="?listType=&amp;sort=&amp;page=1">2</a> | 
          <a href="?listType=&amp;sort=&amp;page=2">3</a> | 
          <a href="?listType=&amp;sort=&amp;page=3">4</a> | 
          <a href="?listType=&amp;sort=&amp;page=1">starší »</a>
        </span>
      </div>
EOD;

  $dom = PHPQuery::newDocument($html);
  var_dump($dom->find('.navigation > .pagination > *')->eq(-2)->text());
  var_dump($dom->find('.navigation > .pagination > *:last-child(2)')->text());

Gives out:
string(0) ""
string(11) "starší »"

And you need 4.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sosnovsky, 2017-05-05
@desiigner

The first thing that came to mind was what can be obtained by counting the total number of elements (this is an option if the method above does not work), that is:

$dom   = PHPQuery::newDocument($html);
$elems = $dom->find('.navigation > .pagination > *');

if( $elems->length ) {
    $penult = $elems->length - ($elems->length > 2 ? 2 : 1);

    var_dump($elems->eq($penult)->text());
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question