PHP programming languages provides a lot of different type of functions for string manipulation. In this tutorial we will look how to find some part of the given specified string or text. We will use popular function named
We will start with the syntax of the
substr() function. This functions have 3 parameters. This function will return a string which is a sub-string of the given string.
string substr(string $string, int $start,[int $length])
As we can see length is optional parameter but
$start are required parameters.
$stringhold the string we want to get some part of.
$indexis the index value we want to start the substring selection.
$lengthis the count of chracters from
Return Given Length From Start
We will start with a simple example. In this example we will provide the
index we want to start and continue to the end which will be a substring. We will start from index 3. Keep in mind that index start from 0 which means
P is index 0. Following example will print
<?php $str="Poftut.com"; echo substr($str,3); //Will print "tut.com" ?>
Return Given Length From Specified Index
In this example we will provide the index and the lenght of sub string we want to return. So we will provide the optional length parameter. We will get sub string which starts from index 3 and length 3 . This will return
<?php $str="Poftut.com"; echo substr($str,3,3); //Will print "tut" ?>
Return Given Length From End or Reverse
We can use negative values for index and length. This will run reverse operation. So first we will start from a negative index. In this example we will start from
-3 to the end. This will print only
<?php $str="Poftut.com"; echo substr($str,-3); //Will print "com" ?>
Return Given Length From Specified Index or Reverse
We can also provide length as negative number which will count in a reverse manner. In this example we will start from 2 but count reverse with
-3 . This will return
<?php $str="Poftut.com"; echo substr($str,2,-3); //Will print "Pof" ?>