PHP substr() Function with Example

By IncludeHelp Last updated : December 27, 2023

PHP substr() Function

The substr() function is a string function in PHP, it is used to get the substring from specified index from the string.

Syntax

The syntax of the substr() function:

substr(string, start, [length]);

Parameters

The parameters of the substr() function:

  • string is the main string.
  • start is the starting index of the string, from where a substring returns.
  • length is an optional parameter, it defines the number of characters to return.

Note: Negative values points to the end of string. For example: -1 points last character, -2 points second last character, -3 points third last character and so on...

Return Value

The return value of this method is string, it returns the portion of string specified by the start and length parameters.

Sample Input/Output

Input:
str = "Hello friends how are your friends?";
start =10
Output:
"nds how are your friends?"

str = "Hello friends how are your friends?";
start =10
length = 5
Output:
"nds h"

Example of PHP substr() Function

<?php
$str = "Hello friends how are your friends?";
	
//returns substring from 10th index to end of the string
$substring = substr($str,10);
echo ($substring . "\n");

//returns substring from 10th index to next 5 chars
$substring = substr($str,10,5);
echo ($substring . "\n");	

//testing with negative values
$substring = substr($str,-1);
echo ($substring . "\n");	

//testing with negative values
$substring = substr($str,10,-1);
echo ($substring . "\n");

//testing with negative values
$substring = substr($str,-5);
echo ($substring . "\n");	

//testing with negative values
$substring = substr($str,3,-5);
echo ($substring . "\n");	
?>

Output

The output of the above example is:

nds how are your friends?
nds h
?
nds how are your friends
ends?
lo friends how are your fri

To understand the above example, you should have the basic knowledge of the following PHP topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.