PHP substr() Function
Topic: PHP String ReferencePrev|Next
Description
The substr()
function extracts a part of a string.
The following table summarizes the technical details of this function.
Return Value: | Returns the extracted part of string; or FALSE on failure, or an empty string. |
---|---|
Changelog: | Since PHP 7.0, if start is equal to the string length, this function returns an empty string ("" ). In earlier versions it returns FALSE . |
Version: | PHP 4+ |
Syntax
The basic syntax of the substr()
function is given with:
The following example shows the substr()
function in action.
Example
Run this code »<?php
// Sample string
$str = "Alice in Wonderland";
// Getting substring
echo substr($str, 0, 5);
?>
Tip: The string positions start at 0, not 1. For instance, in the string "lemon", the character at position 0 is "l", the character at position 1 is "e", and so forth.
Note: If start is greater than the string length, FALSE
will be returned. Also, if length parameter is omitted, the substring starting from start until the end of the string will be returned.
Parameters
The substr()
function accepts the following parameters.
Parameter | Description |
---|---|
string | Required. Specifies the string to work on. |
start |
Required. Specifies the position in the string from where the extraction begins.
|
length |
Optional. Specifies how many characters to extract.
|
More Examples
Here're some more examples showing how substr()
function actually works:
The following example demonstrates the usage of positive and negative start parameter.
Example
Run this code »<?php
// Sample string
$str = "Alice in Wonderland";
// Getting substrings
echo substr($str, 9)."<br>";
echo substr($str, 6, 2)."<br>";
echo substr($str, -4)."<br>";
echo substr($str, -10, 6);
?>
The following example demonstrates the usage of positive and negative length parameter.
Example
Run this code »<?php
// Sample string
$str = "Alice in Wonderland";
// Getting substrings
echo substr($str, 2, 3)."<br>";
echo substr($str, 9, -4)."<br>";
echo substr($str, -13, 2)."<br>";
echo substr($str, -10, -7);
?>