Explain substr() function in PHP


PHP offers different kinds of inbuilt functions having distinctive functionalities. The substr() is a built-in function in PHP and this function works with strings. It is utilized to extricate a part of the string .

The syntax of the substr() is demonstrated below.

substr(string,begin, length)

Now let's discuss the Parameters. Three parameters can be passed to substr() function out of which two are mandatory and one is optional.

string:

In this parameter, we pass the string that necessities to cut or adjust. This is an obligatory parameter

begin position:

This is a mandatory parameter. This implies the position of the string from where the part should be removed. This value should be an integer. In the event that integer is positive then the returned string will start from the starting position mentioned in the input.

In this case, a negative integer indicates that the start position is from the end of the string.

length:

This parameter is discretionary and should be an integer. This means to the length of the part of the string that needs to be cut from the original string. In this case, a positive integer indicates that to begin from start and extract the length from the beginning.

, In this case, a negative integer indicates that the extracted length from the end of the string.

If the integer is negative then it means to begin from start and If nothing is passed, then it will return the string starting from start_position till the end of the string.

Example:

 Live Demo

<?php
   $string1 ="Welcome To Tutorials Point";
   $len = strlen($string1);
   echo substr($string1, 8),"<br/>";
   echo substr($string1, 5, $len),"<br/>";
   echo substr($string1, -5, 3),"<br/>";
?>

Output:

To Tutorials Point
me To Tutorials Point
Poi

Explanation:

In the above example, we have to take a string variable and then we have used substr() function to get the required portion of that string. In the first expression we have mentioned the starting point but no ending point. In the second expression, we have mentioned both the starting and ending point. In the third expression, we have mentioned a negative starting point so it evaluates from the end.

raja
Published on 20-Jun-2019 18:51:43
Advertisements