Home » PHP

PHP substr() Function with Example

PHP substr() Function: Here, we are going to learn about the substr() function with example in PHP.
Submitted by IncludeHelp, on February 06, 2019

PHP substr() Function

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


    substr(string, start, [length]);


  • 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...


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

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

PHP code:

	$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");	


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

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.