PHP Tutorial - PHP substr() Function






Definition

The substr() function gets a substring from a string.

Syntax

PHP substr() Function has the following syntax.

string substr ( string str, int start_pos [, int length] )

Parameter

PHP substr() function takes the following parameters:

  • str - the string to work with
  • start_pos - where you want to start reading from.
  • length - Optional. The number of characters to extract. A negative number extracts from the end of the string. if missing, substr() extracts from the start position to the end




Return

PHP substr() Function returns the sub string.

Example

Use substr to get sub string


<?PHP/*from   w ww  .j  a v  a  2s . co m*/
$message = "This is test from java2s.com"; 
$a = substr($message, 1); 
print $a;
print "\n";
$b = substr($message, 0); 
print $b;
print "\n";
$c = substr($message, 5); 
print $c;
print "\n";
$d = substr($message, 50); 
print $d;
print "\n";
$e = substr($message, 5, 4); 
print $e;
print "\n";
$f = substr($message, 10, 1); 
print $f;
?>

The code above generates the following result.





Example 2

If the third parameter is a negative number, and PHP will omit that number of characters from the end of the string, as opposed to the number of characters you wish to copy:

Negative lengths says something like "copy everything but the last three characters".

A negative start index start from the end. You can use a negative length with your negative start index, like this:


<?PHP/*from  ww  w. j a  v  a 2  s.  co m*/
$string = "this is a test from java2s.com!" ;
$a = substr($string, 5); 
// copy from character five until the end 
print $a;
print "\n";
$b = substr($string, 5, 5); 
// copy five characters from character five 
print $b;
print "\n";
$c = substr($string, 0, -1); 
// copy all but the last character 
print $c;
print "\n";
$d = substr($string, -5); 
// PHP starts 5 characters from the end, then copies from there to the end 
print $d;
print "\n";
$e = substr($string, -5, 4); 
// this uses a negative start and a positive length; PHP starts five 
// characters from the end of the string, then copies four characters
print $e;
print "\n";
$f = substr($string, -5, -4); 
// start five characters from the end, and copy everything but the last four characters
print $f;
?>

The code above generates the following result.