Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP substr() Function

PHP substr() Function

PHP String Reference Manual PHP String Reference Manual

Example

Return "world" from a string:

Run Example »


Definition and Usage

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

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


Syntax

substr(

string,start,length

)

Parameters Description
string Required. Specifies the string to return a part of.
start Required. Specifies where in the string to start.
  • 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 of the string
  • | | *length* | Optional. Specifies the length of the string to return. Default is to the end of the string. |

    Technical Details

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

    More examples

    Example 1

    Use the start parameter with different positive and negative values:

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

    Run Example »

    Example 2

    Use the start and length parameters with different positive and negative values:

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

    PHP String Reference Manual PHP String Reference Manual