PHP substr() Function

PHP substr() Function

The substr() function in PHP returns the portion of the string specified by the start and length parameters.

Syntax

substr ( string $string , int $start [, int $length ] ) 

Parameter

string (required)- This parameter represents the input string. It must be one character or longer.

start (required)- This parameter specifies where to start in the specified string.

  • It start is positive(0<), the returned string will begin at the specified position in the string.
  • If start is negative(0>), the returned string will begin at the specified position from the end of the string.
  • If start is equal to 0, the returned string will begin at the first character in the string.

length (optional)- This parameter represents the length of the returned string

  • If length is positive(0<), the string returned will contain characters beginning from the start.
  • If length is negative(0>), the string returned will contain characters from the end of the string.
  • If length is equal to 0, false or NULL, an empty string will be returned.

Return

This function returns the extracted part of a string or returns FALSE on failure, or for an empty string.

Example 1

   <?php
  //initializing string 1
  $str1= "Hello world";
  echo "Actual String: ".$str1;
// returns a part of a string.
  echo("\nAfter the substr() function… ");
  echo "\nNew String: ".substr("Hello world",6); // return world 
  ?> 
 

Output

Actual String: Hello world
After the substr() function... 
New String: world 

Example 2

 

Output

Actual String: Hello world
After the substr() function... 
New String: orld 

Example 3

 

Output

Actual String: Hello world
After the substr() function... 
New String: o wo 

Example 4

 

Output

Actual String: Hello world
After the substr() function... 
New String: