Summary: in this tutorial, you’ll learn how to use the PHP substr() function to extract a substring from a string.
Introduction to the PHP substr() function #
The substr() function accepts a string and returns a substring from the string.
Here’s the syntax of the substr() function:
substr ( string $string , int $offset , int|null $length = null ) : stringCode language: PHP (php)In this syntax:
$stringis the input string.$offsetis the position at which the function begins to extract the substring.$lengthis the number of characters to include in the substring. If you omit the$lengthargument, thesubstr()function will extract a substring from the$offsetto the end of the$string. If the$lengthis 0, false, or null, thesubstr()function returns an empty string.
PHP substr() function examples #
Let’s take some examples of using the substr() function.
1) Simple PHP substr() function example #
The following example uses the substr() function to extract the first three characters from a string:
<?php
$s = 'PHP substring';
$result = substr($s, 0, 3);
echo $result;// PHPCode language: PHP (php)In this example, the substr() function extract the first 3 characters from the 'PHP substring' string starting at the index 0.