Web Analytics

PHP substr() Function

String Function PHP 4+

The substr() function extracts a portion of a string starting at a specified position.

Syntax

substr(string $string, int $start, ?int $length = null): string

Parameters

ParameterTypeDescription
$stringstringThe input string
$startintStart position (0-based, negative from end)
$lengthint|nullMax characters to extract (optional)

Return Value

Returns the extracted substring, or an empty string if start is beyond string length.

Try It Online

Output
Click Run to execute your code

More Examples

Get First N Characters

<?php
$str = "Hello World";
echo substr($str, 0, 5);  // "Hello"
?>

Get Last N Characters

<?php
$str = "Hello World";
echo substr($str, -5);    // "World"
?>

Remove Last N Characters

<?php
$str = "filename.txt";
echo substr($str, 0, -4); // "filename"
?>
Tip: For multibyte strings (UTF-8), use mb_substr() instead.

Common Use Cases

  • Extracting file extensions
  • Truncating text for previews
  • Parsing fixed-width data
  • Getting parts of timestamps

Related Functions

  • strlen() - Get string length
  • strpos() - Find position of substring
  • mb_substr() - Multibyte safe version