PHP substr() Function

Examples

Returns "world" from the string:

<?php
echo substr("Hello world",6);
?>

Run Examples

Definition and Usage

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

Note:If start the parameter is negative and length less than or equal to startthen length is 0.

Syntax

class="language-php">substr(string,sta rt,length)
Parameter Description
string Required. Specifies the string to return a part of.
start

Required. Specifies where to start in the string.

  • Positive number - starts at the specified position in the string
  • Negative number - starts from the specified position from the end of the string
  • 0 - starts at the first character in the string
length

Optional. Specifies the length of the returned string. The default is to the end of the string.

  • Positive number - from start The length returned from the position of the parameter
  • Negative number - the length returned from the end of the string

Technical Details

Return value: Returns the extracted part of the string, or FALSE if failed, or an empty string.
PHP Version: 4+
Changelog:

In PHP versions 5.2.2 to 5.2.6, if start If the parameter represents a negative truncation or out-of-bounds position, FALSE is returned.

Other versions start from start Starts from the position to get the string.

More examples

Example 1

Using with different positive and negative numbers start Parameters:

<?php
echo substr("Hello world",10)."<br>";
echo substr("Hello world",1)."<br>";
echo substr("Hello world",3)."<br>";
echo substr("Hello world",7)."<br>";
echo substr("Hello world",-1)."<br>";
echo substr("Hello world",-10)."<br>";
echo substr("Hello world",-8)."<br>";
echo substr("Hello world",-4)."<br>";
?>

Run Examples

Example 2

Using with different positive and negative numbers start and length Parameters:

<?php
echo substr("Hello world",0,10)."<br>";
echo substr("Hello world",1,8)."<br>";
echo substr("Hello world",0,5)."<br>";
echo substr("Hello world",6,6)."<br>";
echo substr("Hello world",0,-1)."<br>";
echo substr("Hello world",-10,-2)."<br>";
echo substr("Hello world",0,-6)."<br>";
echo substr("Hello world",-2-3)."<br>";
?>

Run Examples