PHP 字符串截取函数详解332


在 PHP 中,有几个内置函数可以用来截取字符串。这些函数为处理文本和从字符串中提取特定部分提供了方便的方式。

1. substr() 函数

substr() 函数用于从字符串中截取一个子字符串,从指定位置开始到指定长度。语法为:```php
substr(string $str, int $start [, int $length ])
```

其中:* `$str` 是要截取的字符串。
* `$start` 是截取开始的位置(从 0 开始)。
* `$length` 是截取的长度(默认为字符串的剩余部分)。

例如:```php
$str = "Hello World";
// 从第 6 个字符截取到字符串末尾
$substring = substr($str, 6); // 输出:World
// 从第 2 个字符截取 5 个字符
$substring = substr($str, 2, 5); // 输出:llo W
```

2. substring() 函数

substring() 函数与 substr() 函数类似,但它允许负值作为开始位置,表示从字符串末尾开始截取。语法为:```php
substring(string $str, int $start [, int $length ])
```

其中:* `$str` 是要截取的字符串。
* `$start` 是截取开始的位置(正值表示从字符串开头,负值表示从字符串末尾)。
* `$length` 是截取的长度(默认为字符串的剩余部分)。

例如:```php
$str = "Hello World";
// 从倒数第 5 个字符截取到字符串末尾
$substring = substring($str, -5); // 输出:World
// 从倒数第 2 个字符截取 5 个字符
$substring = substring($str, -2, 5); // 输出:ld W
```

3. strstr() 函数

strstr() 函数用于查找字符串中指定子字符串的首次出现位置,并返回从该位置到字符串末尾的子字符串。语法为:```php
strstr(string $str, string $search [, bool $before_needle ])
```

其中:* `$str` 是要搜索的字符串。
* `$search` 是要查找的子字符串。
* `$before_needle`(可选)指定在找到子字符串之前是否返回结果(默认值为 false)。

例如:```php
$str = "Hello World";
// 查找 "World" 并返回从该位置到字符串末尾的子字符串
$substring = strstr($str, "World"); // 输出:World
// 查找 "World" 并返回从该位置之前到字符串末尾的子字符串
$substring = strstr($str, "World", true); // 输出:Hello World
```

4. stristr() 函数

stristr() 函数与 strstr() 函数类似,但它以不区分大小写的方式查找子字符串。语法为:```php
stristr(string $str, string $search [, bool $before_needle ])
```

例如:```php
$str = "Hello World";
// 以不区分大小写的方式查找 "world" 并返回从该位置到字符串末尾的子字符串
$substring = stristr($str, "world"); // 输出:World
```

5. strtok() 函数

strtok() 函数用于使用分隔符将字符串分解为一组令牌。语法为:```php
strtok(string $str, string $delimiter [, string $token ])
```

其中:* `$str` 是要分解的字符串。
* `$delimiter` 是要使用的分隔符。
* `$token`(可选)指定要返回哪个令牌(默认值为第一个令牌)。

例如:```php
$str = "Hello, World, How, Are, You?";
// 使用逗号作为分隔符将字符串分解为令牌
$tokens = strtok($str, ", ");
// 循环遍历令牌
while ($token = strtok(", ")) {
echo $token . ""; // 输出:
// Hello
// World
// How
// Are
// You
}
```

PHP 提供了多种字符串截取函数,使处理文本和从字符串中提取特定部分变得容易。通过了解这些函数的语法和用法,您可以有效地在 PHP 应用程序中操作字符串。

2024-10-11


上一篇:PHP 获取客户端 IP 地址

下一篇:用 PHP 轻松替换字符串中的字符