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
Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces
Use this:
the following code will remove ','. If you have anyother character or sub-string, you may use that instead of ','
// if you have another string account for
Based on @Justin Poliey's regex:
I create a function more similar to substr, and using the idea of @Dave.
Ps.: The full length cut may be less than substr.
I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:
This will return the first 200 characters of words: