What is substr in php

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)
  • $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.
Читайте также:  Visual studio python utf 8

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:

 $s = 'PHP substring'; $result = substr($s, 0, 3); echo $result;// PHPCode language: HTML, XML (xml)

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

PHP substr() function

2) Using PHP substr() function with the default length argument

The following example uses the substr() function to extract a substring from the ‘PHP substring’ string starting from the index 4 to the end of the string:

 $s = 'PHP substring'; $result = substr($s, 4); echo $result; // substringCode language: HTML, XML (xml)

In this example, we omit the $length argument. Therefore, the substr() returns a substring, starting at index 4 to the end of the input string.

PHP substr() function with default length

PHP substr() function with negative offset

The $offset argument can be a negative number. If the $offset is negative, the substr() function returns a substring that starts at the offset character from the end of the string. The last character in the input string has an index of -1 .

The following example illustrates how to use the substr() function with negative offset:

 $s = 'PHP is cool'; $result = substr($s, -4); echo $result; // coolCode language: HTML, XML (xml)

In this example, the substr() returns a substring that at 4th character from the end of the string.

The following picture illustrates how the substr() function works in the above example:

PHP substr() function with negative offset

PHP substr() function with negative length

Like the $offset argument, the $length argument can be negative. If you pass a negative number to the $length argument, the substr() function will omit a $length number of characters in the returned substring.

The following example illustrates how to use the substr() with a negative $offset and $length arguments:

 $s = 'PHP is cool'; $result = substr($s, -7, -5); echo $result; // isCode language: HTML, XML (xml)

The following picture illustrates how the above example works:

PHP substr() function with negative length

The PHP mb_substr() function

See the following example:

 $message = 'adiós'; $result = substr($message, 3, 1); echo $result;Code language: HTML, XML (xml)

This example attempts to extract a substring with one character in the $message string starting at index 3. However, it shows nothing in the output.

The reason is that the $message string contains a non-ASCII character. Therefore, the substr() function doesn’t work correctly.

To extract a substring from a string that contains a non-ASCII character, you use the mb_substr() function. The mb_substr() function is like the substr() function except that it has an additional encoding argument:

mb_substr ( string $string , int $start , int|null $length = null , string|null $encoding = null ) : stringCode language: PHP (php)

The following example uses the mb_substr() function to extract a substring from a string with non-ASCII code:

 $message = 'adiós'; $result = mb_substr($message, 3, 1); echo $result;Code language: HTML, XML (xml)

PHP substr helper function

The following defines a helper function that uses the mb_substr() function to extract a substring from a string:

 function substring($string, $start, $length = null) < return mb_substr($string, $start, $length, 'UTF-8'); >Code language: HTML, XML (xml)

Summary

  • Use the PHP substr() function to extract a substring from a string.
  • Use the negative offset to extract a substring from the end of the string. The last character in the input string has an index of -1 .
  • Use the negative length to omit a length number of characters in the returned substring.
  • Use the PHP mb_substr() function to extract a substring from a string with non-ASCII characters.

Источник

substr

Возвращает подстроку строки string , начинающейся с start символа по счету и длиной length символов.

Список параметров

Входная строка. Должна содержать хотя бы один символ.

Если start неотрицателен, возвращаемая подстрока начинается с позиции start от начала строки, считая от нуля. Например, в строке ‘abcdef‘, в позиции 0 находится символ ‘a‘, в позиции 2 — символ ‘c‘, и т.д.

Если start отрицательный, возвращаемая подстрока начинается с позиции, отстоящей на start символов от конца строки string .

Если string меньше либо содержит ровно start символов, будет возвращено FALSE .

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

$rest = substr ( «abcdef» , — 1 ); // возвращает «f»
$rest = substr ( «abcdef» , — 2 ); // возвращает «ef»
$rest = substr ( «abcdef» , — 3 , 1 ); // возвращает «d»
?>

Если length положительный, возвращаемая строка будет не длиннее length символов, начиная с параметра start (в зависимости от длины string ).

Если length отрицательный, то будет отброшено указанное этим аргументом число символов с конца строки string (после того как будет вычислена стартовая позиция, если start отрицателен). Если при этом позиция начала подстроки, определяемая аргументом start , находится в отброшенной части строки или за ней, возвращается false.

Если указан параметр length и является одним из 0, FALSE или NULL , то будет возвращена пустая строка.

Если параметр length опущен, то будет возвращена подстрока, начинающаяся с позиции, указанной параметром start и длящейся до конца строки.

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

$rest = substr ( «abcdef» , 0 , — 1 ); // возвращает «abcde»
$rest = substr ( «abcdef» , 2 , — 1 ); // возвращает «cde»
$rest = substr ( «abcdef» , 4 , — 4 ); // возвращает false
$rest = substr ( «abcdef» , — 3 , — 1 ); // возвращает «de»
?>

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

Возвращает извлеченную часть строки, или FALSE в случае возникновения ошибки или пустую строку string .

Список изменений

Версия Описание
5.2.2 — 5.2.6 Если параметр start указывает на позицию с отрицательной обрезкой, возвращается FALSE . Другие версии возвращают строку с начала.

Примеры

Пример #3 Базовое использование substr()

echo substr ( ‘abcdef’ , 1 ); // bcdef
echo substr ( ‘abcdef’ , 1 , 3 ); // bcd
echo substr ( ‘abcdef’ , 0 , 4 ); // abcd
echo substr ( ‘abcdef’ , 0 , 8 ); // abcdef
echo substr ( ‘abcdef’ , — 1 , 1 ); // f

// Получить доступ к отдельному символу в строке
// можно также с помощью «квадратных скобок»
$string = ‘abcdef’ ;
echo $string [ 0 ]; // a
echo $string [ 3 ]; // d
echo $string [ strlen ( $string )- 1 ]; // f

Пример #4 substr() и приведение типов

class apple public function __toString () return «green» ;
>
>

echo «1) » . var_export ( substr ( «pear» , 0 , 2 ), true ). PHP_EOL ;
echo «2) » . var_export ( substr ( 54321 , 0 , 2 ), true ). PHP_EOL ;
echo «3) » . var_export ( substr (new apple (), 0 , 2 ), true ). PHP_EOL ;
echo «4) » . var_export ( substr ( true , 0 , 1 ), true ). PHP_EOL ;
echo «5) » . var_export ( substr ( false , 0 , 1 ), true ). PHP_EOL ;
echo «6) » . var_export ( substr ( «» , 0 , 1 ), true ). PHP_EOL ;
echo «7) » . var_export ( substr ( 1.2e3 , 0 , 4 ), true ). PHP_EOL ;
?>

Результат выполнения данного примера:

1) 'pe' 2) '54' 3) 'gr' 4) '1' 5) false 6) false 7) '1200'

Ошибки

Возвращает FALSE в случае ошибки.

Смотрите также

  • strrchr() — Находит последнее вхождение символа в строке
  • substr_replace() — Заменяет часть строки
  • preg_match() — Выполняет проверку на соответствие регулярному выражению
  • trim() — Удаляет пробелы (или другие символы) из начала и конца строки
  • mb_substr() — Возвращает часть строки
  • wordwrap() — Переносит строку по указанному количеству символов
  • Посимвольный доступ и изменение строки

Источник

substr in PHP: An Ultimate Guide to substr() Function

substr in PHP

PHP is an open source scripting language which is used widely. The code is executed on the server and is free of cost. It is easy to learn for beginners and at the same time powerful enough to run Facebook. With PHP, one can generate dynamic page content, collect form data, receive and send cookies, encrypt data, handle data in database and files on the server. PHP offers a range of functions that make it easy to work with different data types. In this tutorial, we are going to explore substr in PHP.

What is substr in PHP?

substr in PHP is a built-in function used to extract a part of the given string. The function returns the substring specified by the start and length parameter. It is supported by PHP 4 and above. Let us see how we can use substr() to cut a portion of the string.

Syntax

The substr in php has the following syntax:

substr(string, starting_position, length_of_substring)

The function returns an extracted part of the string if the starting_position is found in the string. Otherwise, an empty string or False is returned. [1]

Example:

We want the function to return “in php” from the string.

echo substr(«substr in php»,6);

Output:

substr_in_PHP_1

Stand Out From Your Peers this Appraisal Season

Parameter Values

The substr in PHP function has three arguments or parameters. One parameter is optional, and the other two are mandatory.

1. string: This parameter includes the original string, i.e., the string which needs to be modified or cut. It is a required parameter. The input string must at least be one character.

2. starting_position: This parameter includes the position, which is the index from where the part of the string needs to be extracted. The input is an integer, and it is a required parameter.

  • If the integer is positive, the returned string starts from that position in the string. The first character is counted as zero.
  • If the integer is negative, the returned string starts from that position from the end of the string. The counting begins from 1 at the end of the string.
  • If the starting_position is greater than the string size, then the function returns FALSE.

3. length_of_substring: This is an optional parameter, and it is an integer value referring to the length of the string cut from the original one.

  • If the length is positive, then the substring includes the number of characters passed in this parameter beginning from the starting_position.
  • If the length is negative, then the substring begins from the starting_position and extracts the length from the string’s end. Many characters are omitted from the end if the length passed is negative.
  • If the length parameter is zero, null or False will be returned
  • If the parameter is not passed, then the function returns a string starting from starting_position till the end.

Here are some examples to explain the use of these parameters:

1. Positive Starting Position

echo »

Original: $str

«;

echo »

Susbtring: $sub_str

«;

Output:

substr_in_PHP_2.

2. Negative Starting Position

echo »

Original: $str

«;

echo »

Susbtring: $sub_str

«;

Output:

substr_in_PHP_3.

3. Positive Starting Position and Length

echo »

Original: $str

«;

echo »

Susbtring: $sub_str

«;

Output:

substr_in_PHP_4

4. Negative Starting Position and Length

echo »

Original: $str

«;

echo »

Susbtring: $sub_str

«;

Output:

substr_in_PHP_5.

Here’s How to Land a Top Software Developer Job

5. Positive Length and Negative Starting Position

echo »

Original: $str

«;

echo »

Substring: $sub_str

«;

Output:

substr_in_PHP_6

6. Negative Length and Positive Starting Position

echo »

Original: $str

«;

echo »

Substring: $sub_str

«;

Output:

substr_in_PHP_7

Conclusion

In this substr in PHP tutorial, we learned about substr function, its use, and syntax. If you are interested in learning more about PHP and web development, do not forget to check out Simplilearn’s Full-stack web development certification. On the other hand, with Simplilearn’s free learning platform SkillUp, you can learn the most in demand skills in software development too. Enroll today and get ahead in your PHP career now!

About the Author

Simplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Post Graduate Program in Full Stack Web Development

Full Stack Web Developer — MEAN Stack

*Lifetime access to high-quality, self-paced e-learning content.

Источник

Оцените статью