Very often, we need to use PHP to cut off or truncate a long string of words or text. A very typical example is that we have many posts in our blog or website. We wish to show the most recent 10 posts in the homepage. Actually all posts have very long contents, with about 300 words per post. If all contents of the 10 posts are displaying on the homepage, the homepage will be very long and congested, and seems never ending by scrolling down the page again and again.
In face, this is just an example, I believe nobody will do this that way. A good solution is to display only the first 100 or 150 words of each posts to attract attention of visitors. If a visitor is interested in a topic, he or she can click on the “read more” link to access the post and continue the reading.
PHP preg_replace() function
This result can easily be achieved by using regular expression with PHP. The PHP preg_replace() function can easily perform a regular expression with search and replace.
This is much easier to explain with an example:
// This is the string of words that need to be truncated
$string= “In short, PHP is part of the HTML document with the .php file extension. PHP is the most popular Server Side Language for webpage design nowadays. Most of the powerful and interesting interactive websites on the Internet are written in PHP web language. Therefore PHP is almost the must-to-learn webpage design language if you want to create interactive website. New tutorials will constantly add this PHP Tutorials blog. Please come back often. “;
// Define the length of words to be truncated
$length = 100;
// Truncate the string
$string = preg_replace(‘/\s+?(\S+)?$/’, ”, substr($string, 0, $length));
// Display the results
echo $string . ” ……”;
The results display on the screen after running the above PHP codes is:
In short, PHP is part of the HTML document with the .php file extension. PHP is the most popular ……
PHP Example File:
This post discuss how to use PHP to cut off or truncate a long string of words.