English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP substr() Function Usage and Example

   PHP String Character String Functions Manual

    The substr() function is used to return a substring of the string.

Syntax

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

Definition and Usage

 Returns a substring of the string string specified by the start and length parameters.

Return Value

It returns a part of the string

Parameter

Serial NumberParameters and Description
1

string

Required. Specifies the input string. It must have at least one character.

2

start

Required. It specifies where to start 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

3

length

It specifies the length of the string to be returned. The default is to the end of the string.
  • Positive - Return from the position of the start parameter

  • Negative - Return from the end of the string

Online Example

Try the following example, returning "Krishna" from the string:

<?php
   //Returns "Krishna" from the string
   echo substr("Sairam Krishna",6).'<br>';
   
   //Using the start parameter with different positive and negative numbers:
   echo substr("abcdef", 0, -1).'<br>'; // Returns "abcde"
   echo substr("abcdef", 2, -1).'<br>'; // Returns "cde"
   echo substr("abcdef", 4, -4).'<br>'; // Returns ""
   echo substr("abcdef", -3, -1); // Returns "de"   
?>
Test and see‹/›

Output Result

Krishna
abcde
cde
de

PHP String Character String Functions Manual