Show A Part Of String – substr in PHP

by Hiroshi on August 18, 2008

in PHP Basics, PHP Functions, substr

Recently I was working with some PHP project and I had to fetch some text from database but I did not want to show all the paragraph. Instead I wanted to display just some part of it and give the reader facility to have a link or read more.

For example:
If the original text is
PHP is a great programming platform where we can do anything relating to dynamic web pages and huge websites.
I wanted to display just a part of it like this.
PHP is a great programming platform…

In this case we use substr which returns a part of string. It means substr returns the portion of string specified by the start and length parameters.

In the following example we collect starting and ending part of data. i.e.

<?php
$data="PHP is a great programming platform where we can do anything relating to dynamic web pages and huge websites";
$data1 = substr($data, 0, 35);
$data2 = substr($data, -17);
echo "$data1 ..."; // returns "PHP is a great programming platform ..."
echo "$data2"; // returns "and huge websites"
?>

and

<?php
$result = substr("abcdef", -1);    // returns "f"
$result = substr("abcdef", 1);    // returns "bcdef"
$result = substr("abcdef", 2, -1);  // returns "cde"
$result = substr("abcdef", 0, -3);  // returns "abc"
?>

You have to give string, starting point and ending point.
0 means from start.
2 means after two characters from start
-2 means drop two characters from the end

Suppose we have a string containing date and we want to collect the data from date in parts of year, month and day.

<?php
$date = 140708;
$day   = substr($date, 0, 2);
$month = substr($date,2, 2);
$year  = substr($date, -2);
echo "$day - $month - $year"; //returns "14 - 07 - 08"
?>

more reference from php home

Related Posts

Previous post:

Next post: