PHP substr()
Published May 4, 2022Updated Jul 17, 2023
Contribute to Docs
The substr() function returns a portion of a string specified by parameters for offset and length.
Syntax
substr($string, $offset, $length)
The substr() function takes three parameters:
$string: a requiredstringfrom which a portion will be returned.$offset: a requiredintthat specifies the start of the substring in the following manner:- Positive or zero values specify the zero-based character position from the start of the
string. - Negative values indicate the character position from the end of the
string. - A value greater than the length of
$stringwill return an emptystring.
- Positive or zero values specify the zero-based character position from the start of the
$length: an optionalintthat specifies the number of characters to return in the following manner:- Positive values specify to return that number of characters, or characters up to the end of
$stringif fewer than$lengthcharacters are left after$offsetis determined. - A
nullor omitted value will return characters from$offsetuntil the end of$string. - Negative values will return characters from
$offsetuntil$lengthcharacters from the end of$string. - A value of zero, or a negative value that specifies a position before
$offset, will return an emptystring.
- Positive values specify to return that number of characters, or characters up to the end of
Example
The following example uses the substr() function to return a substring from the given string. Then the echo command prints this new string to the console:
<?phpecho (substr("I am learning PHP.", 14, 3));?>
The example will result in the following output:
PHP
Codebyte Example
The following example gives three examples of the substr() function operating on the same string.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours