Home  >  Article  >  Backend Development  >  What is the php function to get the first digits of a string?

What is the php function to get the first digits of a string?

hzc
hzcOriginal
2020-06-19 14:48:183260browse

What is the php function to get the first digits of a string?

#What is the function in php to get the first few digits of a string?

Usage of substr function:

substr Returns the substring of string

Instructions: string substr (string $string, int $ start [, int $length ] )

Returns the substring of string string specified by the start and length parameters.

Parameters

string

Input string .

start

  • If start is a non-negative number, the returned string will start from the start position of string and start counting from 0. For example, in the string "abcdef", the character at position 0 is "a", the character at position 2 is "c", and so on.

  • If start is a negative number, the returned string will start from the start character forward from the end of string.

  • If the length of string is less than or equal to start, FALSE will be returned.

<?php
$rest = substr(“abcdef”, -1); // 返回 “f”
$rest = substr(“abcdef”, -2); // 返回 “ef”
$rest = substr(“abcdef”, -3, 1); // 返回 “d”
?>

length

  • If a positive length is provided, the returned string will start at start at most Contains length characters (depending on the length of string).

  • If a negative length is provided, many characters at the end of the string will be missed (if start is a negative number, it will be counted from the end of the string). If start is not in this text, an empty string will be returned.

  • If length is supplied with a value of 0, FALSE or NULL, an empty string will be returned.

  • If length is not provided, the returned substring will start at the start position and continue until the end of the string.

<?php
$rest = substr(“abcdef”, 0, -1); // 返回 “abcde”
$rest = substr(“abcdef”, 2, -1); // 返回 “cde”
$rest = substr(“abcdef”, 4, -4); // 返回 “”
$rest = substr(“abcdef”, -3, -1); // 返回 “de”
?>

Recommended tutorial: "php tutorial"

The above is the detailed content of What is the php function to get the first digits of a string?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn