You are here

function _advanced_text_formatter_get_html_length in Advanced Text Formatter 7

Calculate max length of HTML source to get the maximum of $max_length visible characters.

Parameters

string $text: HTML source.

int $max_length: Maximum number of visible characters.

1 call to _advanced_text_formatter_get_html_length()
advanced_text_formatter_trim_text in ./advanced_text_formatter.module
Trim text.

File

./advanced_text_formatter.module, line 486
Advanced Text Formatter

Code

function _advanced_text_formatter_get_html_length($text, $max_length) {
  $length = 0;
  $html_length = 0;

  // Split input on HTML tags and entities. The result is an array where each
  // odd item is HTML markup.
  $parts = preg_split('/(<[^>]+>|&[^;]+;)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  for ($i = 0; $i < count($parts); ++$i) {
    if ($length >= $max_length) {

      // Already reached the maximum length. Stop counting.
      break;
    }
    $part_length = drupal_strlen($parts[$i]);
    if (!($i & 1)) {

      // This is a text item. Add this part up to where we reach the max length.
      $add_length = min($max_length - $length, $part_length);
      $html_length += $add_length;
      $length += $add_length;
    }
    elseif (drupal_substr($parts[$i], 0, 1) == '&') {

      // This is an HTML entity. Count this as a single character.
      ++$length;
      $html_length += $part_length;
    }
    else {

      // Invisible HTML element. Always add whole element.
      $html_length += $part_length;
    }
  }
  return $html_length;
}