Current Location: Home> Function Categories> substr

substr

Return part of the string
Name:substr
Category:String
Programming Language:php
One-line Description:Returns part of the string.

Definition and usage

substr() function returns part of the string.

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

Example

Example 1

Return "world" from the string:

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

Try it yourself

Example 2

Use start parameters 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>" ;
?>

Try it yourself

Example 3

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

Try it yourself

grammar

class="language-php">substr( string , sta rt , length )
parameter describe
string Required. Specifies that some of the strings are returned.
start

Required. Specifies where to start in the string.

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

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

  • Positive number - the length returned from the position where the start parameter is located
  • Negative number - length returned from the end of the string
Similar Functions