substr() function in PHP


The substr() function is used to return a part of a string.

Syntax

substr(str, begin, len)

Parameters

  • str − The string

  • begin − Specifies where to begin in the string

    • A positive number  − Start at a specified position in the string

    • A negative number  − Start at a specified position from the end of the string

    • − Start at the first character in string

  • len  − Specifies the length of the returned string. Default is to the end of the string.

    • A positive number  − The length to be returned from the start parameter

    • Negative number  − The length to be returned from the end of the string

Return

The substr() function returns the extracted part of the string.

Example

The following is an example −

 Live Demo

<?php
echo substr("This is it!",5);
?>

Output

is it!

Example

The following is an example −

 Live Demo

<?php
echo substr("programming language",2,6)."<br>"
?>

Output

ogramm <br>

Example

Let us see another example that includes negative parameters −

 Live Demo

<?php
echo substr("website development",-5,-2)."<br>"
?>

Output

pme <br>

Updated on: 24-Jun-2020

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements