Skip to content

Instantly share code, notes, and snippets.

@DimaMinka
Forked from dikiyforester/get-word-count.php
Created May 11, 2018 06:46
Show Gist options
  • Save DimaMinka/6bb0fb052131d75366ef6b57ccdcbcc7 to your computer and use it in GitHub Desktop.
Save DimaMinka/6bb0fb052131d75366ef6b57ccdcbcc7 to your computer and use it in GitHub Desktop.
Return information about words used in a string prior PHP 5.3
<?php
/**
* Counts words in a text string.
*
* Uses code from wp_trim_words().
*
* @param string $text Given text.
*/
function my_get_word_count( $text = '' ) {
$translations = get_translations_for_domain( 'default' );
$translation = $translations->translate( 'words', 'Word count type. Do not translate!' );
$words_array = array();
$text = wp_strip_all_tags( $text );
// Use code from wp_trim_words().
if ( strpos( $translation, 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
preg_match_all( '/./u', $text, $words_array );
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $text, null, PREG_SPLIT_NO_EMPTY );
}
return count( $words_array );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment