Home > Backend Development > PHP Tutorial > PHP: Introduction to the usage differences between substr and substring

PHP: Introduction to the usage differences between substr and substring

伊谢尔伦
Release: 2023-03-11 09:52:01
Original
3725 people have browsed it

Everyone knows that the string interception characters in js have functions substr and sub string, what about PHP? PHP does not have a directly available substring function, but it does have a substr function.

If you don’t believe it, you can test it yourself. A correct piece of code is given below.

<?
$a="me";
echo(substr($a,,));//输出me
?>
下面又给出一段错误的代码
<?
$a="me";
echo(subString($a,,));
?>
Copy after login

substr() function returns a part of a string.

substr(string,start,length)

string: The string to be intercepted

start:

Positive number - starts at the specified position in the string
Negative number - starts at the specified position from the end of the string
0 - starts at the first character in the string

length:

Optional. Specifies the length of the string to be returned. The default is until the end of the string.
Positive number - Return from the position of the start parameter
Negative number - Return from the end of the string

Detailed explanation of the usage of PHP substr()

Definition and usage

## The #substr() function returns a portion of a string. Using the substr() function to intercept Chinese may cause garbled characters. It is recommended to use the mb_substr() function to intercept Chinese.

Syntax

substr(string,start,length)

Required. Specifies a part of the string to be returned.
ParametersDescription
##string
startRequired. Specifies where in the string to begin.

  • 正数 - 在字符串的指定位置开始

  • 负数 - 在从字符串结尾的指定位置开始

  • 0 - 在字符串中的第一个字符处开始

length

可选。规定要返回的字符串长度。默认是直到字符串的结尾。

  • 正数 - 从 start 参数所在的位置返回

  • 负数 - 从字符串末端返回

提示和注释

注释:如果 start 是负数且 length 小于等于 start,则 length 为 0。

例子

<?php
$str = &#39;hello world!&#39;;
echo substr($str, 4); // o world! 左起第4开始向右截取到末尾
echo substr($str, 4, 5); // o wor 左起第4开始向右取5位
echo substr($str, 4, -1); // o world 左起第4与右起第1之间的字符
echo substr($str, -8, 4); // o wo 右起第8开始向右截取4位
echo substr($str, -8,-2); // o worl 右起第8与右起第2之间的字符
?>
Copy after login

The above is the detailed content of PHP: Introduction to the usage differences between substr and substring. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template