PHP substr() Function

PHP substr() Function is used to return a part of a string. PHP substr() function is PHP built-in function.

Syntax for substr:

substr(string $string, int $start, int $length) ;

Parameter,

$string : Required. It is input string to extract a part of string.

$start : Required. It is position where to begin in the string.

  1. A positive number - Returned string will start at a specified position in the string.
  2. A negative number - Returned string will start at a specified position from the end of the string.
  3. 0 - Returned string will start at the first character in string.

$length : Optional. It is the length of the returned string. Default is to the end of the string.

  1. A positive number - The length to be returned from the start parameter.
  2. A Negative number - The length to be returned from the end of the string.
  3. If the length parameter is 0, NULL, or FALSE - it return an empty string.


Return Values for substr:

The substr() function returns the extracted part of the string called sub string. It also returns FALSE on failure or an empty string.

Let's see below example to understand php substr() Function in details.

Example :

<?php
$str = "Learn php substr() function tutorial with example.";
echo "<br>Original String : ".$str;
echo "<br><br><b>Extracted part of the string according to Parameter values.</b><br>";
echo "<br>".substr($str,5);
echo "<br>".substr($str,-6);
echo "<br>".substr($str,0);
echo "<br>".substr($str,7,9);
echo "<br>".substr($str,8,-5);
echo "<br>".substr($str,-13,-6);
echo "<br>".substr($str,-10,15);
?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

99828