Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

php - Get first 100 characters from string, respecting full words

I have asked a similar question here before, but I need to know if this little tweak is possible. I want to shorten a string to 100 characters and use $small = substr($big, 0, 100); to do so. However, this just takes the first 100 characters and doesn't care whether it breaks up a word or not.

Is there any way to take up to the first 100 characters of a string but make sure you don't break a word?

Example:

$big = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!"

$small = some_function($big);

echo $small;

// OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"

Is there a way to do this using PHP?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All you need to do is use:

$pos=strpos($content, ' ', 200);
substr($content,0,$pos ); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...