Tips Tricks Tutorials

WEB-NES-BAY

Learn Tips and tricks on Linux, Hacking, linux, PHP, Perl, Web, Hardware

bookmark bookmark
WEBNESBAY On August - 23 - 2009

If you have an article in your site and Typically you would want to display the 5 to 10 words summary with a “Read More” the full article link as in joomla. The substr function would be an easy solution except that it does not bother about the word boundaries. Here is the code for

<?php
 function word_split($str,$words=15) {
	$arr = preg_split("/[\s]+/", $str,$words+1);
	$arr = array_slice($arr,0,$words);
	return join(' ',$arr);
}
//Usage
$input = 'This is the test for truncating long string along word boundaries in PHP.
In PHP. PHP is a powerful tool for making dynamic and interactive Web pages.
PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.
In our PHP tutorial you will learn about PHP, and how to execute scripts on your server..';

echo word_split($input,10);
?>

Output:
 This is the test for truncating long string along word boundaries in PHP


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.

The first parameter is the regular expressions pattern along which the string is to be split. In this, we split the string across word boundaries. Therefore we use a predefined character class \s which matches whitespace characters such as space, tab, carriage return and line feed.

The second parameter is the long text string which we want to split in to some limited boundary.

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.

I am giving the example below

<?php
 $str = 'first second third fourth fifth';
 print_r(preg_split("/[\s]+/", $str, 4));
?>

This would output:

Array
(
 [0] => first
 [1] => second
 [2] => third
 [3] => fourth fifth
)

Related posts:

  1. Top 10 php optimization tips
  2. Captalization of strings in PHP
  3. Generating PDF files with PHP and FPDF
  4. Decorators in Python
  5. PHP Cookies tutorial a quick guide
Categories: PHP

One Response

  1. Amit Patekar says:

    cool peace of code, thank you, i was searching for this simple login from long time. :)

Leave a Reply