The PHP substr() function is used to get the substring that is returns a part of a string. This function takes the begin and length parameters to return the portion of string.

Note:

If the start position parameter is a negative number and length is less than or equal to start parameter, length becomes 0.

Syntax

substr(string,start,length)

string – This parameter is required and of string type. Returns the part of a string from a string.

Start – This parameter is required and of integer type. It Specifies wherever to start within the string

                A positive integer – Start at a given position within the string.

                A negative integer – Start at a given position from the end of the string.

                0 – Start at the initial character in string.

Length – This parameter is optional and of integer type. It specifies the length of the returned string. Default is the end of the string.

                A positive integer – The length to be returned from the beginning parameter.

                A Negative integer – The length to be returned from the end of the string.

<?php
$str = "Welcome to PHP!";
echo substr($str, 0, 6); // Outputs: Welcom
echo '<br>';
echo substr($str, 0, -6); // Outputs: Welcome t
echo '<br>';
echo substr($str, 0); // Outputs: Welcome to PHP!
echo '<br>';
echo substr($str, -6, 4); // Outputs: o PH
echo '<br>';
echo substr($str, -6); // Outputs: o PHP!
echo '<br>';
echo substr($str, -11); // Outputs: ome to PHP!
?>