WF AQ

Knowledge base

Tagliare un testo aggiungendo i puntini di sospensione

Questo blocco di codice può essere usato nel file functions.php di WordPress.

/**
 * Plugin Name: Cut text
 *
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to (positivo: taglia allo spazio; negativo: taglia al carattere)
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @param bool $allowable string with tags allowed
 * @return string
 */
function cut_text($input, $length, $ellipses = true, $strip_html = true, $allowable = 'all') {

	$input=str_replace("[","<",$input); 
	$input=str_replace("\""," ",$input); 

	//strip tags, if desired
	if ($strip_html) {
		$input = strip_tags($input);
	}elseif($allowable != 'all'){
		$input = strip_tags($input,$allowable);
	}

	//no need to trim, already shorter than trim length
	if (strlen($input) <= abs($length)) {
		return $input;
	}

	if ( $length >= 0 ) {
		//find last space within length
		$last_space = strrpos(substr($input, 0, $length), ' ');
		$trimmed_text = substr($input, 0, $last_space);
	} else {
		$trimmed_text = substr($input, 0, abs($length));
	}

	//add ellipses (...)
	if ($ellipses) {
		$trimmed_text .= ' ...';
	}

	return $trimmed_text;
}