You are here

public function Data::wordCount in Translation Management Tool 8

Calculates number of words, which a text consists of.

Parameters

string $text:

Return value

int Returns count of words of text.

File

src/Data.php, line 107

Class

Data
All data-related functions.

Namespace

Drupal\tmgmt

Code

public function wordCount($text) {

  // Strip tags in case it is requested to not include them in the count.
  if ($this->config
    ->get('word_count_exclude_tags')) {
    $text = strip_tags($text);
  }

  // Replace each punctuation mark with space.
  $text = str_replace(array(
    '`',
    '~',
    '!',
    '@',
    '"',
    '#',
    '$',
    ';',
    '%',
    '^',
    ':',
    '?',
    '&',
    '*',
    '(',
    ')',
    '-',
    '_',
    '+',
    '=',
    '{',
    '}',
    '[',
    ']',
    '\\',
    '|',
    '/',
    '\'',
    '<',
    '>',
    ',',
    '.',
  ), ' ', $text);

  // Remove duplicate spaces.
  $text = trim(preg_replace('/ {2,}/', ' ', $text));

  // Turn into an array.
  $array = $text ? explode(' ', $text) : array();

  // How many are they?
  $count = count($array);

  // That is what we need.
  return $count;
}