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
Usage:
This will output first 10 words.
The
preg_split
function is used to split a string into substrings. The boundaries along which the string is to be split, are specified using a regular expressions pattern.preg_split
function takes 4 parameters, but only the first 3 are relevant to us right now.First Parameter – Pattern The first parameter is the regular expressions pattern along which the string is to be split. In our case, we want to split the string across word boundaries. Therefore we use a predefined character class
\s
which matches white space characters such as space, tab, carriage return and line feed.Second Parameter – Input String The second parameter is the long text string which we want to split.
Third Parameter – Limit The third parameter specifies the number of substrings which should be returned. If you set the limit to
n
, preg_split will return an array of n elements. The firstn-1
elements will contain the substrings. The last(n th)
element will contain the rest of the string.And there you have it — a reliable method of truncating any string to the nearest whole word, while staying under the maximum string length.
I've tried the other examples above and they did not produce the desired results.
Here you go:
Description:
^
- start from beginning of string([\s\S]{1,200})
- get from 1 to 200 of any character[\s]+?
- not include spaces at the end of short text so we can avoidword ...
instead ofword...
[\s\S]+
- match all other contentTests:
regex101.com
let's add toor
few otherr
regex101.com
orrrr
exactly 200 characters.regex101.com
after fifthr
orrrrr
excluded.Enjoy.
I would use the preg_match function to do this, as what you want is a pretty simple expression.
The expression means "match any substring starting from the beginning of length 1-200 that ends with a space." The result is in $result, and the match is in $matches. That takes care of your original question, which is specifically ending on any space. If you want to make it end on newlines, change the regular expression to:
I believe this is the easiest way to do it:
I'm using the special characters to split the text and cut it.