PHP substr() Function with Example

PHP substr() Function with Example

PHP substr() Function: Here, we will find out about the substr() work with the example in PHP.

PHP substr() Function

substr() work is a string capacity in PHP, it is utilized to get the substring from indicated file from the string.

Syntax:

    substr(string, start, [length]);

Here,

  • the string is the principal string.
  • the start is the beginning record of the string, from where a substring returns.
  • length is a discretionary parameter, it characterizes the number of characters to return.

Note: Negative values focus as far as possible of string. For example – 1 focuses the last character, – 2 focuses second last character, – 3 focuses third keep the going character, etc…

Example:

    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"

PHP Code:

<?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:

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

Recent Posts

error: Alert: Content is protected!!