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

Chủ Đề