DimaMinka
5/11/2018 - 6:46 AM

Return information about words used in a string prior PHP 5.3

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 );
}