PHP programming languages provide a lot of different types of functions for string manipulation. In this tutorial, we will look at how to find some part of the given specified string or text. We will use the popular function named
PHP substr() Syntax
We will start with the syntax of the
substr() function. This function has 3 parameters. This function will return a string which is a substring 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 at index 3. Keep in mind that the index starting from 0 which means P is index 0. The 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 length of substring we want to return. So we will provide the optional length parameter. We will get substring which starts at 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 a 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" ?>