substr обрезать строку PHP

Содержание
Введение
Синтаксис
Параметры
Возвращаемые значения
Похожие статьи

Введение

Для получения части строки в PHP используется функция substr()

Она появилась в PHP 4 и с тех пор присутствует в PHP 5, PHP 7, PHP 8

Синтаксис

Функция substr используется следующим образом

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

Возвращает часть строки, заданную параметрами offset и length.

Параметры

string

Строка, с которой будет работать функция.

offset

If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If offset is negative, the returned string will start at the offset'th character from the end of string.

If string is less than offset characters long, an empty string will be returned.

Пример #1 Использование отрицательного значения offset

<?php $rest= substr("abcdef", -1); // вернёт "f" $rest= substr("abcdef", -2); // вернёт "ef" $rest= substr("abcdef", -3, 1); // вернёт "d" ?>

length

If length is given and is positive, the string returned will contain at most length characters beginning from offset (depending on the length of string).

If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a offset is negative). If offset denotes the position of this truncation or beyond, an empty string will be returned.

If length is given and is 0, false or null, an empty string will be returned.

If length is omitted, the substring starting from offset until the end of the string will be returned.

Пример #2 Использование отрицательного значения length

<?php $rest= substr("abcdef", 0, -1); // вернёт "abcde" $rest= substr("abcdef", 2, -1); // вернёт "cde" $rest= substr("abcdef", 4, -4); // вернёт ""; prior to PHP 8.0.0, false was returned $rest= substr("abcdef", -3, -1); // вернёт "de" ?>

Возвращаемые значения

Функция substr() возвращает часть строки или пустую строку.