PHP substr

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:

  • $string is the input string.
  • $offset is the position at which the function begins to extract the substring.
  • $length is the number of characters to include in the substring. If you omit the $length argument, the substr() function will extract a substring from the $offset to the end of the $string. If the $length is 0, false, or null, the substr() 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)

Try it

In this example, the substr() function extract the first 3 characters from the 'PHP substring' string starting at the index 0.