PHP substr()Function

PHP String 参考手册PHP String Reference Manual

Example

Return "world" from the string:

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

Run example »

Definition and Usage

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

Note:If the start parameter is a negative number and length is less than or equal to start, then length is 0.


Syntax

substr(string,start,length)

Parameter Description
string Required. Specifies the string from which to return a part.
start Required. Specifies where to begin in the string.
  • Positive - Start at the specified position in the string
  • Negative - Start at the specified position from the end of the string
  • 0 - Start at the first character in the string
length Optional. Specifies the length of the string to return. Default is until the end of the string.
  • Positive - Return from the position specified by the start parameter
  • Negative - Return from the end of the string

Technical Details

Return value: Returns the extracted part of the string, or FALSE on failure, or an empty string.
PHP Version: 4+
Changelog: In PHP 5.2.2 to 5.2.6, if the start parameter indicates a negative truncation or out-of-bounds position, FALSE is returned. In other versions, the string is fetched starting from the start position.


More Examples

Example 1

Using the start parameter with different positive and negative numbers:

<?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 example »

Example 2

Using the start and length parameters with different positive and negative numbers:

<?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>"; ?>


PHP String 参考手册PHP String Reference Manual Other Extensions