Opciones para truncar cadenas - Trucos CSS

Anonim

Técnica # 1: Simple

function myTruncate($string, $limit, $break=".", $pad="… ") ( if(strlen($string) <= $limit) return $string; if(false !== ($breakpoint = strpos($string, $break, $limit))) ( if($breakpoint < strlen($string) - 1) ( $string = substr($string, 0, $breakpoint) . $pad; ) ) return $string; )

Técnica # 2: Simple

function ellipsis($text, $max=100, $append='… ') ( if (strlen($text) <= $max) return $text; $out = substr($text,0,$max); if (strpos($text,' ') === FALSE) return $out.$append; return preg_replace('/\w+$/','',$out).$append; )

Uso:

Técnica # 3: Más opciones

Opciones para usar php_tidy de PHP para reparar HTML roto o para eliminar HTML por completo.

function summarise( $input, $break = " ", $end_text = "… ", $limit = 255, $tidy_html = 1, $strip_html = 0 ) ( if ( strlen( $input ) >= $limit ) ( $breakpoint = strpos( $input, $break, $limit ); $input = substr( $input, 0, $breakpoint ) . $end_text; ) if ( $tidy_html == 1 ) ( ob_start( ); $tidy = new tidy; $config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true ); $tidy->parseString( $input, $config, 'utf8' ); $tidy->cleanRepair( ); $input = $tidy; ) if ( $strip_html == 1 ) ( $input = strip_tags( $input ); ) return $input; )

Técnica # 4: Sin función

 $max_length) ( $short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long $short_text .= "… "; // add an ellipses… at the end $short_text .= "Read more"; // add a link echo $short_text; ) else ( // string is already less than $max_length, so display the string as is echo $long_text; ) ?>