Hướng dẫn truncate php

Im looking for a soluting for the followting case. I have a string

"This is a long string of words"

I want to use only the first few words, but if I just cut everything after 20th character, it will look like this:

"This is a long strin"

I can grab first 3 words

implode(' ', array_slice(explode(' ', "This is a long string of words"), 0, 3));

But in some cases, 3 words are going to be too short "I I I".

How can I grab as many words as possible before 20th character?

Rob

12.5k4 gold badges36 silver badges54 bronze badges

asked Jul 6, 2013 at 22:11

4

echo array_shift(explode("\n", wordwrap($text, 20)));

Documentation:

  • array_shift
  • explode
  • wordwrap

answered Jul 6, 2013 at 22:23

RobRob

12.5k4 gold badges36 silver badges54 bronze badges

1

Before I give you an answer in PHP, have you considered the following CSS solution?

overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;

This will result in the text being cut off at the most appropriate place and an ellipsis ... marking the cut-off.

If this is not the effect you're looking for, try this PHP:

$words = explode(" ",$input);
// if the first word is itself too long, like hippopotomonstrosesquipedaliophobia‎
// then just cut that word off at 20 characters
if( strlen($words[0]) > 20) $output = substr($words[0],0,20);
else {
    $output = array_shift($words);
    while(strlen($output." ".$words[0]) <= 20) {
        $output .= " ".array_shift($words);
    }
}

answered Jul 6, 2013 at 22:21

0

Not the answer you're looking for? Browse other questions tagged php string or ask your own question.

Để dễ dàng tiếp thu bài hướng dẫn này thì trước tiên bạn cần xem qua hàm ltrim() và rtrim()

- Hàm trim() được dùng để: "Xóa những ký tự có tên trong danh sách ký tự do bạn chỉ định ra khỏi vị trí đầu tiên và cuối cùng của chuỗi. Việc xóa ở vị trí đầu tiên (hoặc cuối cùng) sẽ kết thúc khi ký tự đầu tiên (hoặc cuối cùng) của chuỗi không nằm trong danh sách ký tự do bạn chỉ định".

- Lưu ý: Hàm này sẽ trả về một chuỗi mới chứ không làm thay đổi giá trị của chuỗi ban đầu.

1) Cú pháp

- Để sử dụng hàm trim() thì chúng ta sử dụng cú pháp như sau:

trim(string, charlist)
Tham sốYêu cầuMô tả
string Bắt buộc - Chuỗi được dùng để xử lý
charlist Không bắt buộc

- Danh sách những ký tự mà bạn muốn xóa ra khỏi đầu & cuối chuỗi

- Lưu ý: Nếu bỏ qua tham số charlist, tất cả những ký tự bên dưới nếu chúng có tồn tại ở đầu hoặc cuối chuỗi thì chúng sẽ bị xóa.

  • \0 (NULL)
  • \t (tab)
  • \n (new line)
  • \x0B (vertical tab)
  • \r (carriage return)
  •     (white space)

- Trước khi đi vào tìm hiểu các ví dụ thì bạn cần phải biết rằng:

- Những ký tự \0 \t \n \x0B \r     sẽ không có hiển thị đặc biệt gì lên màn hình.

- Ví dụ, chúng ta có một đoạn mã như sau:








- Màn hình trình duyệt sẽ hiển thị là:

Tài liệu học HTML

- Tuy nhiên, khi bạn phải bấm vào Xem nguồn trang (view-source) thì mới thấy được sự khác biệt:





      Tài 


liệu                học 
HTML

2) Một số ví dụ

- Xóa tất cả những ký tự M ra khỏi vị trí đầu & cuối của chuỗi MMMTài liệu học HTMLMMMM


Xem ví dụ

- Xóa tất cả những ký tự M T L à ra khỏi vị trí đầu & cuối của chuỗi Tài liệu học HTML


Xem ví dụ

The obvious thing to do is read the documentation.

But to help: substr($str, $start, $end);

$str is your text

$start is the character index to begin at. In your case, it is likely 0 which means the very beginning.

$end is where to truncate at. Suppose you wanted to end at 15 characters, for example. You would write it like this:


and you would get this:

long text that 

makes sense?

EDIT

The link you gave is a function to find the last white space after chopping text to a desired length so you don't cut off in the middle of a word. However, it is missing one important thing - the desired length to be passed to the function instead of always assuming you want it to be 25 characters. So here's the updated version:

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

So in your case you would paste this function into the functions.php file and call it like this in your page:

$post = the_post();
echo truncate($post, 100);

This will chop your post down to the last occurrence of a white space before or equal to 100 characters. Obviously you can pass any number instead of 100. Whatever you need.