Hướng dẫn truncate php
Im looking for a soluting for the followting case. I have a string Show
I want to use only the first few words, but if I just cut everything after 20th character, it will look like this:
I can grab first 3 words
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
Documentation:
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?
This will
result in the text being cut off at the most appropriate place and an ellipsis If this is not the effect you're looking for, try this PHP:
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:
- 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à:
- 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:
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:
and you would get this:
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:
So in your case you would paste this function into the functions.php file and call it like this in your page:
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. |