Php truncate string by words
By using the wordwrap function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line: Show
One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:
Also, here is the PHPUnit testclass used to test the implementation:
EDIT :Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:
Konrad Kiss 6,8061 gold badge19 silver badges21 bronze badges answered Sep 17, 2008 at 4:27
Grey PantherGrey Panther 12.6k6 gold badges44 silver badges64 bronze badges 9 This will return the first 200 characters of words:
answered Sep 17, 2008 at 4:41
mattmacmattmac 2,0253 gold badges17 silver badges16 bronze badges 8
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. answered Jan 12, 2011 at 4:29
DaveDave 5294 silver badges6 bronze badges 4 The following solution was born when I've noticed a $break parameter of wordwrap function:
Here is the solution:
Example #1.
The above example will output:
Example #2.
The above example will output:
answered Jul 25, 2013 at 8:10
2 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. answered Sep 17, 2008 at 6:08
Garrett AlbrightGarrett Albright 2,8043 gold badges27 silver badges44 bronze badges Use strpos and substr:
This will give you a string truncated at the first space after 30 characters.
lajlev 7322 gold badges7 silver badges21 bronze badges answered Sep 17, 2008 at 4:29
Lucas OmanLucas Oman 15.3k2 gold badges44 silver badges45 bronze badges 1 Here you go:
answered Sep 17, 2008 at 4:31
UnkwnTechUnkwnTech 85.2k65 gold badges183 silver badges227 bronze badges 2 Here is my function based on @Cd-MaN's approach.
answered Mar 26, 2010 at 12:36
CamsoftCamsoft 11.4k19 gold badges80 silver badges120 bronze badges
Description:
Tests:
Enjoy. answered Jul 3, 2014 at 15:04
Artem PArtem P 4,8305 gold badges40 silver badges41 bronze badges 2 It's surprising how tricky it is to find the perfect solution to this problem. I haven't yet found an answer on this page that doesn't fail in at least some situations (especially if the string contains newlines or tabs, or if the word break is anything other than a space, or if the string has UTF-8 multibyte characters). Here is a simple solution that works in all cases. There were similar answers here, but the "s" modifier is important if you want it to work with multi-line input, and the "u" modifier makes it correctly evaluate UTF-8 multibyte characters.
One possible edge case with this... if the string doesn't have any whitespace at all in the first $characterCount characters, it will return the entire string. If you prefer it forces a break at $characterCount even if it isn't a word boundary, you can use this:
One last option, if you want to have it add ellipsis if it truncates the string...
answered Sep 1, 2015 at 20:55
orrdorrd 8,8994 gold badges37 silver badges30 bronze badges 2 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. answered Nov 9, 2011 at 22:29
tanctanc 2413 silver badges10 bronze badges
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:
answered Sep 17, 2008 at 4:33
Justin PolieyJustin Poliey 16.3k7 gold badges37 silver badges48 bronze badges 1 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.
answered Oct 26, 2011 at 14:37
Yo-LYo-L 4771 gold badge4 silver badges12 bronze badges
Usage:
This will output first 10 words. The
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 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 answered Apr 5, 2012 at 9:32
Bud DamyanovBud Damyanov 28.3k6 gold badges41 silver badges52 bronze badges You can use this:
Examples:
EditHow it's work: 1. Explode space from input text:
for example, if
2. For each word: Select each element in exploded text:
Append current word(
Then add 1 to
Then return
answered Mar 10, 2021 at 6:27
HOSSEIN BHOSSEIN B 1751 silver badge6 bronze badges Based on @Justin Poliey's regex:
answered Dec 9, 2010 at 16:28
amateur baristaamateur barista 4,2403 gold badges24 silver badges37 bronze badges 1 I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:
answered Jun 13, 2014 at 11:37
This is how i did it:
Jazi 6,43412 gold badges58 silver badges90 bronze badges answered Dec 11, 2014 at 10:33
While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+. You can use the
Simple Truncation https://3v4l.org/QJDJU
Result
Expanded Truncation https://3v4l.org/FCD21Since Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.
Result
Results using
answered Apr 3, 2020 at 23:50
Will B.Will B. 16.4k4 gold badges61 silver badges67 bronze badges I know this is old, but...
answered Feb 26, 2013 at 12:48
gosukiwigosukiwi 1,5591 gold badge27 silver badges43 bronze badges 1 I create a function more similar to substr, and using the idea of @Dave.
Ps.: The full length cut may be less than substr. answered Jun 24, 2015 at 15:03
evandro777evandro777 5714 silver badges4 bronze badges Added IF/ELSEIF statements to the code from Dave and AmalMurali for handling strings without spaces
answered Jan 28, 2016 at 12:04
answered Dec 2, 2020 at 3:42
1
Truncate the text surrounding a specific set of keywords.The goal is to be able to convert this:
Into this:
Which is a very common situation when displaying search results, excerpts, etc. To achieve this we can use these two methods combined:
Now you can do:
Run code. answered Oct 11, 2021 at 20:24
JesusIniestaJesusIniesta 8,2681 gold badge28 silver badges20 bronze badges 1 I find this works:
The buffer allows you to adjust the length of the returned string.
mickmackusa 39k11 gold badges76 silver badges113 bronze badges answered May 11, 2018 at 11:00
answered Dec 18, 2021 at 18:51
2 I used this before
answered Feb 9, 2014 at 13:24
Yousef AltafYousef Altaf 2,4944 gold badges47 silver badges69 bronze badges I believe this is the easiest way to do it:
I'm using the special characters to split the text and cut it. answered Mar 9, 2018 at 13:26
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
answered Dec 22, 2018 at 9:01
Mahbub AlamMahbub Alam 3522 silver badges6 bronze badges May be this will help someone:
answered Apr 1, 2014 at 10:32
slash3bslash3b 513 silver badges8 bronze badges How do I limit string words in PHP?function limit_text($text, $limit) { if (str_word_count($text, 0) > $limit) { $words = str_word_count($text, 2); $pos = array_keys($words); $text = substr($text, 0, $pos[$limit]) . '...'; } return $text; } echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
How do I cut a string after a specific character in PHP?The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.
How do you short a string in PHP?Cutting a string to a specified length is accomplished with the substr() function. For example, the following string variable, which we will cut to a maximum of 30 characters. $string = 'This string is too long and will be cut short.
How do you split the first 5 characters of a string?You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.
|