Forum Moderators: coopster

Message Too Old, No Replies

Counting HTML attributes on a page

         

csdude55

3:06 am on Apr 26, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have something like this on every page:

<div data-b="[0-9]+" ...>...</div>


In jQuery, I'm finding the last instance using:

var lB = $('[data-b]').last().data('b');


(Shout out to Fotiman for helping me with that one)

But can you guys suggest a way to get the same value using PHP? I would need to run it on the footer page that's included on every page of the site, finding the last "data-b" value on the page that included it, up to that point. So it needs to be fast, and put minimal stress on the server and minimal impact on load time.

I know that I could use cURL to read the entire page into a string, but that seems like overkill and slow if it's on every page.

As an alternative, I could go through every page and manually create a variable at the end for the value.

But I'm hoping that you guys can suggest an easier option that wouldn't be as slow as cURL and that I wouldn't have to modify every page.

Peter_S

9:50 am on Apr 26, 2017 (gmt 0)

5+ Year Member Top Contributors Of The Month



I am not sure I understood exactly what you need, but here is a little code. I didn't test it, so be careful.

$html contains your page code. For example, you can put a "ob_start" at the beginning of the PHP script outputting the html, and retrieve the code using one of the "ob_get_xxx" functions, depending of your needs.

Also, my code is very simple, and works only if you are sure of the format of your attribute (double quotes), if you need something more flexible and deal with all kind of parameters formatting, you'll certainly need regexp, or use the DOMDocument PHP class, to explore the whole page accurately.


$search = ' data-b=' ;

$pos = strrpos ( $html , $search ) ;

$last = false ;

if ( $pos !== false )
{
$start = strpos ( $html, '"' , $pos + strlen ( $search ) ) ;

if ( $start !== false )
{
$start ++ ;
$end = strpos ( $html, '"' , $start ) ;

if ( $end !== false )
{
$last = substr ( $html, $start , $end - $start ) ;
}
}
}



$last should contain the last attribute, or "false" if nothing was found.

ps: sorry, for some reasons, I am not succeeding to put indentation into my code. I tried the code and quote tags, but each time it removes my spaces.