Skip to main content

Truncate long string along word boundaries

Suppose you have a articles module on you website which displays the summary of top three articles in the left column. Typically you would want to display the 10 or 15 words summary with a “Read More” link to the full article. The substr function would be an easy solution except that it does not bother about the word boundaries.

Code

preg_split to the rescue

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 four parameters but only the first three 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 first n-1 elements will contain the substrings. The last (n th) element will contain the rest of the string.

For example see the below code:

This would output:

Leave a Reply

Your email address will not be published. Required fields are marked *

*