這將返回給定的字符串基於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);
?>
的可能重複[PHP - 切後X字符的字符串(http://stackoverflow.com/questions/3161816/php-cut-a-string-after-x-characters) – iconoclast 2014-08-02 06:12:43
我只想指出省略號是一個字符:'...'!='...'並表示爲&hellip; – 2015-11-25 16:22:34
MySQL提供給您的SUBSTRING領域的能力,併爲省略號,你可以使用的情況下,如:選擇(情況下,當長度(場)> 50,然後CONCAT(SUBSTRING(場,1,47),「...」)其他場結束)... – MediaVince 2016-03-23 16:51:41