strip_tags remove ent_quotes ejemplo php string strlen

remove - Agregar... si la cadena es demasiado larga PHP



strip_tags() (10)

Esto devolverá una cadena dada con puntos suspensivos basados ​​en el recuento de palabras en vez de caracteres:

<?php /** * Return an elipsis given a string and a number of words */ function elipsis ($text, $words = 30) { // Check if string has more than X words if (str_word_count($text) > $words) { // Extract first X words from string preg_match("/(?:[^/s,/.;/?/!]+(?:[/s,/.;/?/!]+|$)){0,$words}/", $text, $matches); $text = trim($matches[0]); // Let''s check if it ends in a comma or a dot. if (substr($text, -1) == '','') { // If it''s a comma, let''s remove it and add a ellipsis $text = rtrim($text, '',''); $text .= ''...''; } else if (substr($text, -1) == ''.'') { // If it''s a dot, let''s remove it and add a ellipsis (optional) $text = rtrim($text, ''.''); $text .= ''...''; } else { // Doesn''t end in dot or comma, just adding ellipsis here $text .= ''...''; } } // Returns "ellipsed" text, or just the string, if it''s less than X words wide. return $text; } $description = ''Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quibusdam ut placeat consequuntur pariatur iure eum ducimus quasi perferendis, laborum obcaecati iusto ullam expedita excepturi debitis nisi deserunt fugiat velit assumenda. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt, blanditiis nostrum. Nostrum cumque non rerum ducimus voluptas officia tempore modi, nulla nisi illum, voluptates dolor sapiente ut iusto earum. Esse? Lorem ipsum dolor sit amet, consectetur adipisicing elit. A eligendi perspiciatis natus autem. Necessitatibus eligendi doloribus corporis quia, quas laboriosam. Beatae repellat dolor alias. Perferendis, distinctio, laudantium? Dolorum, veniam, amet!''; echo elipsis($description, 30); ?>

Tengo un campo de descripción en mi base de datos MySQL, y accedo a la base de datos en dos páginas diferentes, en una página muestro todo el campo, pero en el otro, solo quiero mostrar los primeros 50 caracteres. Si la cadena en el campo de descripción tiene menos de 50 caracteres, entonces no se mostrará ..., pero si no lo está, lo mostraré ... después de los primeros 50 caracteres.

Ejemplo (cadena completa):

Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don''t know how long maybe around 1000 characters. Anyway this should be over 50 characters now ...

Exmaple 2 (primeros 50 caracteres):

Hello, this is the first example, where I am going ...


La forma PHP de hacer esto es simple:

$out = strlen($in) > 50 ? substr($in,0,50)."..." : $in;

Pero puedes lograr un efecto mucho más agradable con este CSS:

.ellipsis { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }

Ahora, suponiendo que el elemento tenga un ancho fijo, el navegador se dividirá automáticamente y agregará ... para usted.


Puede usar str_split() para esto

$str = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don''t know how long maybe around 1000 characters. Anyway this should be over 50 characters know..."; $split = str_split($str, 50); $final = $split[0] . "..."; echo $final;


Use wordwrap() para truncar la cadena sin romper palabras si la cadena tiene más de 50 caracteres, y simplemente agregue ... al final:

$str = $input; if( strlen( $input) > 50) { $str = explode( "/n", wordwrap( $input, 50)); $str = $str[0] . ''...''; } echo $str;

De lo contrario, use soluciones que hagan substr( $input, 0, 50); romperá palabras


Uso esta solución en mi sitio web. Si $ str es más corto, que $ max, no se modificará. Si $ str no tiene espacios entre los primeros $ max caracteres, se cortará brutalmente en $ max position. De lo contrario, se agregarán 3 puntos después de la última palabra completa.

function short_str($str, $max = 50) { $str = trim($str); if (strlen($str) > $max) { $s_pos = strpos($str, '' ''); $cut = $s_pos === false || $s_pos > $max; $str = wordwrap($str, $max, '';;'', $cut); $str = explode('';;'', $str); $str = $str[0] . ''...''; } return $str; }


Usted puede lograr el ajuste deseado de esta manera también:

mb_strimwidth("Hello World", 0, 10, "...");

Dónde:

  • Hello World : la cuerda para recortar.
  • 0 : número de caracteres desde el comienzo de la cadena.
  • 10 : la longitud de la cuerda recortada.
  • ... : una cadena adicional al final de la cuerda recortada.

Esto devolverá Hello W...

¡Observe que 10 es la longitud de la cadena truncada + la cadena añadida!

Documentación: http://php.net/manual/en/function.mb-strimwidth.php


$string = "Hello, this is the first example, where I am going to have a string that is over 50 characters and is super long, I don''t know how long maybe around 1000 characters. Anyway this should be over 50 characters know..."; if(strlen($string) >= 50) { echo substr($string, 50); //prints everything after 50th character echo substr($string, 0, 50); //prints everything before 50th character }


<?php $string = ''This is your string''; if( strlen( $string ) > 50 ) { $string = substr( $string, 0, 50 ) . ''...''; }

Eso es.


<?php function truncate($string, $length, $stopanywhere=false) { //truncates a string to a certain char length, stopping on a word if not specified otherwise. if (strlen($string) > $length) { //limit hit! $string = substr($string,0,($length -3)); if ($stopanywhere) { //stop anywhere $string .= ''...''; } else{ //stop on a word. $string = substr($string,0,strrpos($string,'' '')).''...''; } } return $string; } ?>

Uso el fragmento de código anterior varias veces ...


if (strlen($string) <=50) { echo $string; } else { echo substr($string, 0, 50) . ''...''; }