Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

substr

Returns part of a string, counting in bytes.

Syntax

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

Parameters

ParameterTypeDescription
$stringstringThe source string.
$offsetintThe start position, counting from zero. A negative value counts from the end.
$length?intOptional. How many bytes to take; to the end of the string by default.

Return value

stringThe selected part of the string.

Examples

The first characters and the tail of a string:

<?php
 
echo substr('programming', 0, 7), "\n";
echo substr('programming', -4);

Output:

program
ming

A file extension:

<?php
 
$file = 'photo.jpeg';
 
echo substr($file, strrpos($file, '.') + 1);

Output:

jpeg

Notes

The function counts bytes, so it cuts non-ASCII letters in half. Use mb_substr() for text in any language.

See also

  • mb_substr — Returns part of a string.
  • strpos — Finds the position of the first occurrence of a substring.

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.