PHP substr() Function

PHP substr() function is “used to return a part(portion) of a string.”

Syntax

substr($string, start, length)

Parameters

  1. $string(required): It is an input string.
  2. start(required): It is the position where to start the extraction. The first character is at index 0. If the start is non-negative, the returned string will begin with the start‘th position in the string, counting from zero. So, for instance, in the string ‘abcdef,’ the character at position 0 is ‘a‘, the character at position 2 is ‘c, and so forth. If the start is negative, the returned string will start at the start‘th character from the end of the string.
  3. length(optional):  If it is given and is positive, the string returned will contain at most $length characters, depending on the length of the string. If $length is negative, then that many characters will be omitted from the end of the string. If $length is omitted, the substring starting from $start until the end of the string will be returned.

Return value

It returns the extracted part of the string if successful otherwise FALSE or an empty string on failure.

Visual Representation of Pass Negative parameter

Visual Representation of PHP substr() Function

Example 1: How to Use substr() function

<?php

$str = "AppDividend";

echo substr($str, 3)."\n";
echo substr($str, 5)."\n";
echo substr($str, 9)."\n";

Output

Dividend
vidend
nd

Example 2: Pass Negative parameterVisual Representation of Pass Negative parameter

<?php

$str = "AppDividend";
echo substr($str, -2)."\n";
echo substr($str, -5)."\n";
echo substr($str, -8)."\n";

Output

nd
idend
Dividend

Example 3: Using length parameter

<?php

$str = "AppDividend";

// Positive:
echo substr($str, 0,3)."\n";
echo substr($str, 5,6)."\n";

// Negative:
echo substr($str, -8,-4)."\n";
echo substr($str, -5,-1)."\n";

Output

App
vidend
Divi
iden

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.