방지하려면 중간 단어 자르기, 나는 기본적으로 이미 그 능력을 가지고 있기 때문에 먼저 wordwrap()
을 찾습니다.
그래서 내가 취해야 할 접근법은 wordwrap()
을 사용하여 원하는 총 길이의 절반에서 분리 기호 문자열의 길이를 뺀 값으로 세그먼트를 분할하는 것입니다.
그런 다음 wordwrap()
의 첫 번째 줄, 구분 기호 및 마지막 줄을 결합하십시오. (explode()
을 사용하여 wordwrap()
출력을 줄로 나누십시오).
// 3 params: input $string, $total_length desired, $separator to use
function truncate($string, $total_length, $separator) {
// The wordwrap length is half the total minus the separator's length
// trim() is used to prevent surrounding space on $separator affecting the length
$len = ($total_length - strlen(trim($separator)))/2;
// Separate the output from wordwrap() into an array of lines
$segments = explode("\n", wordwrap($string, $len));
// Return the first, separator, last
return reset($segments) . $separator . end($segments);
}
그것을 밖으로 시도 : http://codepad.viper-7.com/ai6mAK
$s1 = "The quick brown fox jumped over the lazy dog";
$s2 = "Lorem ipsum dolor sit amet, nam id laudem aliquid. Option utroque interpretaris eu sea, pro ea illud alterum, sed consulatu conclusionemque ei. In alii diceret est. Alia oratio ei duo.";
$s3 = "This is some other long string that ought to get truncated and leave some stuff on the end of it.";
// Fox...
echo truncate($s1, 30, "...");
// Lorem ipsum...
echo truncate($s2, 30, "...");
// Other one
echo truncate($s3, 40, "...");
출력을 :
The quick...the lazy dog
Lorem ipsum...ei duo.
This is some...on the end of it.
공지 사항이 출력의 마지막 비트 ei duo
조금 짧은 것을. 최종 줄 wordwrap()
이 반환 된 것이 전체 길이가 아니기 때문입니다. 마지막 요소의 strlen()
을 $segments
배열에서 검사하여 일부 임계 값 (예 : $len/2
)보다 작 으면 배열 요소를 explode()
의 단어로 분리하고 다른 단어 앞에 추가하여 작업 할 수 있습니다 그 배열에서.
길이의 반 이상이 끝날 때까지 wordwrap()
에서 두 번째 마지막 줄로 역 추적하고 단어가 튀어 나오는 문제를 해결 한 개선 된 버전입니다. 조금 더 복잡하지만 더 만족스러운 결과를 얻습니다. http://codepad.viper-7.com/mDmlL0
function truncate($string, $total_length, $separator) {
// The wordwrap length is half the total, minus the separator's length
$len = (int)($total_length - strlen($separator))/2;
// Separate the output from wordwrap() into an array of lines
$segments = explode("\n", wordwrap($string, $len));
// Last element's length is less than half $len, append words from the second-last element
$end = end($segments);
// Add words from the second-last line until the end is at least
// half as long as $total_length
if (strlen($end) <= $total_length/2 && count($segments) > 2) {
$prev = explode(' ', prev($segments));
while (strlen($end) <= $total_length/2) {
$end = array_pop($prev) . ' ' . $end;
}
}
// Return the first, separator, last
return reset($segments) . $separator . $end;
}
// Produces:
The quick...over the lazy dog
Lorem ipsum...Alia oratio ei duo.
This is some other...stuff on the end of it.
길이 20은 어디에 적합합니까? 샘플 문자열 출력은 실제로 32이므로 20시에 "빠른 ... 게으른 개"가 될 것입니까? –