2012-07-11 74 views
72

我在我的MySQL數據庫中有一個描述字段,並且我在兩個不同的頁面上訪問數據庫,其中一個頁面顯示整個字段,但另一方面,我只想顯示前50個字符。如果描述字段中的字符串少於50個字符,則不會顯示...,但如果不顯示,我將在前50個字符後顯示...。添加...如果字符串太長PHP

例(完全字符串):

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 ... 

〔實施例2(第50位):

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

的可能重複[PHP - 切後X字符的字符串(http://stackoverflow.com/questions/3161816/php-cut-a-string-after-x-characters) – iconoclast 2014-08-02 06:12:43

+0

我只想指出省略號是一個字符:'...'!='...'並表示爲… – 2015-11-25 16:22:34

+0

MySQL提供給您的SUBSTRING領域的能力,併爲省略號,你可以使用的情況下,如:選擇(情況下,當長度(場)> 50,然後CONCAT(SUBSTRING(場,1,47),「...」)其他場結束)... – MediaVince 2016-03-23 16:51:41

回答

212

這樣做的PHP的方法很簡單:

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

但你可以用這個CSS實現更好的效果:

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

現在,假設元素具有固定的寬度,瀏覽器將自動斷開併爲您添加...

+9

+1對於CSS替代 – Tchoupi 2012-07-11 13:50:56

+2

我認爲css的方式將增加傳輸的數據,而不是移動瀏覽器所需的。更重要的是,你發送全文,而有些時候它不應該可用。 – szamil 2014-02-11 11:36:05

+8

我在CSS替代方案中遇到的主要問題是它不適用於多行。如果你的50個字符換行了2行,那麼再跟第二行說再見。除非有另外的選擇,我還沒有找到? *公司希望* – 2014-08-06 05:58:04

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

我用上面的代碼片斷許多-A-倍..

1
<?php 
$string = 'This is your string'; 

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

就是這樣。

25

使用wordwrap()截斷字串沒有打破的話如果字符串的長度超過50個字符長,只是在末尾添加...

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

echo $str; 

否則,使用該做substr($input, 0, 50);將打破單詞的解決方案。

+0

這個解決方案也不錯,所以我不必打破這些詞......謝謝。 – 2012-07-11 14:35:51

+0

不錯,謝謝! – 2016-03-05 02:40:38

+2

注意,wordwrap不支持多字節字符,並且沒有烘焙的mb_wordwrap函數。 – MarcGuay 2016-09-07 17:40:06

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

您可以使用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; 
105

您可以也以此方式達到理想的裝飾:

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

其中:

  • Hello World:字符串修剪。
  • 0:字符串開始處的字符數。
  • 10:修剪的字符串的長度。
  • ...:在修剪的字符串末尾添加的字符串。

這將返回Hello W...

請注意,10是截斷的字符串+添加的字符串的長度!

文檔:http://php.net/manual/en/function.mb-strimwidth.php

+3

當CSS不是一個選項時,絕對是最簡單的解決方案。 – Guillochon 2014-02-19 16:20:30

+4

優雅的解決方案。正如[這些評論](http://php.net/manual/en/function.define.php)所見。爲了防止被截斷的文本和省略號之間的尾隨空格,您可能需要使用RTRIM(mb_strimwidth($字符串,0,24))。「......」 – 2015-09-01 20:11:48

+1

最佳的CSS恕我直言,選擇是偉大的,但對AJAX有時候你想盡可能少交換數據! – MediaVince 2016-03-23 16:30:28

2

我用我的網站上該解決方案。如果$ 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; 
} 
1

這將返回給定的字符串基於WORD省略號數而不是字符:

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