I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last word before 200 chars.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Keeping track of variable instances
- how to split a list into a given number of sub-lis
May be this will help someone:
This is a small fix for mattmac's answer:
The only difference is to add a space at the end of $string. This ensures the last word isn't cut off as per ReX357's comment.
I don't have enough rep points to add this as a comment.
Ok so I got another version of this based on the above answers but taking more things in account(utf-8, \n and   ; ), also a line stripping the wordpress shortcodes commented if used with wp.
This is how i did it:
I find this works:
function abbreviate_string_to_whole_word($string,$max_length,$buffer) {
}
The buffer allows you to adjust the length of the returned string.
Keep in mind whenever you're splitting by "word" anywhere that some languages such as Chinese and Japanese do not use a space character to split words. Also, a malicious user could simply enter text without any spaces, or using some Unicode look-alike to the standard space character, in which case any solution you use may end up displaying the entire text anyway. A way around this may be to check the string length after splitting it on spaces as normal, then, if the string is still above an abnormal limit - maybe 225 characters in this case - going ahead and splitting it dumbly at that limit.
One more caveat with things like this when it comes to non-ASCII characters; strings containing them may be interpreted by PHP's standard strlen() as being longer than they really are, because a single character may take two or more bytes instead of just one. If you just use the strlen()/substr() functions to split strings, you may split a string in the middle of a character! When in doubt, mb_strlen()/mb_substr() are a little more foolproof.