Добавить … если строка слишком длинная PHP

У меня есть поле описания в моей базе данных MySQL, и я обращаюсь к базе данных на двух разных страницах, на одной странице я показываю все поле, а с другой, я просто хочу отображать первые 50 символов. Если строка в поле описания меньше 50 символов, то она не будет отображаться …, но если это не так, я покажу … после первых 50 символов.

Пример (Полная строка):

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 (первые 50 символов):

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

PHP-способ сделать это прост:

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

Но с этим CSS вы можете добиться гораздо более приятного эффекта:

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

Теперь, если элемент имеет фиксированную ширину, браузер автоматически оборвется и добавит ... для вас.

Вы также можете добиться желаемой отделки:

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

Где:

  • Hello World : строка для обрезки.
  • 0 : количество символов от начала строки.
  • 10 : длина обрезанной строки.
  • ... : добавленная строка в конце обрезанной строки.

Это вернет Hello W...

Обратите внимание, что 10 – это длина укороченной строки + добавленная строка!

Документация: http://php.net/manual/en/function.mb-strimwidth.php

Используйте wordwrap() чтобы усечь строку без разрыва слов, если строка длиннее 50 символов и просто добавьте ... в конец:

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

В противном случае, используя решения, которые выполняют substr( $input, 0, 50); сломает слова.

 if (strlen($string) <=50) { echo $string; } else { echo substr($string, 0, 50) . '...'; } 
 <?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; } ?> 

Я использую вышеприведенный фрагмент кода много раз.

Я использую это решение на своем веб-сайте. Если $ str меньше, чем $ max, оно останется неизменным. Если $ str не имеет пробелов между первыми символами $ max, это будет жестоко разрезано в позиции $ max. В противном случае после последнего целого слова будут добавлены 3 точки.

 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; } 
 <?php $string = 'This is your string'; if( strlen( $string ) > 50 ) { $string = substr( $string, 0, 50 ) . '...'; } 

Вот и все.

 $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 } 

Вы можете использовать str_split() для этого

 $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; 

Это вернет заданную строку с многоточием на основе WORD count вместо символов:

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