PHP substr

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

PHP : substr() function

Description

The substr() function used to cut a part of a string from a string, starting at a specified position.

Version

(PHP 4 and above)

Syntax

substr(string_name, start_pos, length_to_cut) 

Parameters

Name

Description

Required /
Optional

Type

string_name

The input string.

Required

String

start_pos

Refers to the position of the string to start cutting.
A positive number : Start at the specified position in the string.
A negative number : Start at a specified position from the end of the string.

Required

Integer

length_to_cut

Length of the string to cut from the main string.
A positive number : Start at the specified position in the string. 
A negative number : Start at a specified position from the end of the string.

Optional

Integer

Return value

Returns the extracted part of string and false when failure.

Value Type : String.

Pictorial Presentation

string_substr

Example - 1 :

  1. $string1="Welcome to tutorialtours.com";  

  2. echo $string1;  

  3. echo '
    ';  

  4. echo substr($string1,1);  

  5. echo '
    ';  

  6. echo substr($string1,1,5);  

  7. echo '
    ';  

  8. echo substr($string1,0,10);  

  9. echo '
    ';  

  10. echo substr($string1,-1,1);  

  11. echo '
    ';  

  12. ?>  

Output :

Welcome to tutorialtours.com
elcome to tutorialtours.com
elcom
Welcome to
m

Example - 2 :

  1. $string1="Welcome to tutorialtours.com";  

  2. echo $string1;  

  3. echo '
    ';  

  4. echo substr($string1,0,-1);  

  5. echo '
    ';  

  6. echo substr($string1,3,-3);  

  7. echo '
    ';  

  8. echo substr($string1,4,-4);  

  9. echo '
    ';  

  10. echo substr($string1,-3,-2);  

  11. echo '
    ';  

  12. ?>  

Output :

Welcome to tutorialtours.com
Welcome to tutorialtours.co
come to tutorialtours.
ome to tutorialtours
c

Example - 3 :

  1. $string1="Welcome to tutorialtours.com";  

  2. echo $string1;  

  3. echo '
    ';  

  4. echo substr($string1,-1);  

  5. echo '
    ';  

  6. echo substr($string1,-4);  

  7. echo '
    ';  

  8. echo substr($string1,-5,1);  

  9. ?>  

Output :

Welcome to tutorialtours.com
m
.com
e