Skip to content

PHP string functions API

PHP 内置的数组函数 —— PHP 数组既可用作列表也可用作有序映射。

1 class · 7 methods

数组函数

7 methods

用于操作 PHP 多功能数组类型的面向过程的数组函数。

strlen(string $string): int

将一个或多个元素推入 array 的末尾。返回新的元素数量。

Parameters

NameTypeDescription
arraystring输入数组(按引用传递)。

Returns

int

Example

php
<?php
echo strlen("hello");  // 5
echo strlen("日本語"); // 9 (UTF-8 bytes)
strpos(string $haystack, string $needle, int $offset = 0): int|false

弹出并返回数组的最后一个值,将其缩短一个元素。

Parameters

NameTypeDescription
arraystring输入数组(按引用传递)。
needlestringSubstring to find.
offsetintSearch starting offset (default 0).

Returns

int|false

Example

php
<?php
$pos = strpos("Hello, World", "World");
if ($pos !== false) {
    echo $pos;  // 7
}
substr(string $string, int $offset, ?int $length = null): string

计算数组或 Countable 对象中所有元素的数量。

Parameters

NameTypeDescription
valuestring数组或 Countable 对象。
modeintCOUNT_RECURSIVE 用于计算多维数组。
length?intMaximum length (null = to end).

Returns

string

Example

php
<?php
echo substr("Hello, World", 7);     // "World"
echo substr("Hello, World", 7, 3);  // "Wor"
echo substr("Hello", -3);           // "llo"
str_replace(array|string $search, array|string $replace, string|array $subject): string|array

将回调函数应用于给定数组的元素并返回一个新数组。

Parameters

NameTypeDescription
callbackarray|string要应用的函数(null = 值数组)。
arrayarray|string输入数组。
subjectstring|arrayString/array being searched.

Returns

string|array

Example

php
<?php
echo str_replace("world", "PHP", "hello world");  // "hello PHP"
echo str_replace(["a", "b"], "x", "abc");         // "xxc"
strtolower(string $string): string

使用回调函数过滤数组元素。不带回调函数时,移除假值。

Parameters

NameTypeDescription
arraystring输入数组。

Returns

string

Example

php
<?php
echo strtolower("HELLO World");  // "hello world"
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

将一个或多个数组的元素合并在一起。重新索引数字键。

Parameters

NameTypeDescription
arraysstring要合并的数组。
stringstringInput string.
limitintMaximum number of elements.

Returns

array

Example

php
<?php
$parts = explode(",", "a,b,c");
// ["a", "b", "c"]
$parts2 = explode(",", "a,b,c", 2);
// ["a", "b,c"]
trim(string $string, string $characters = " \n\r\t\v\x00"): string

检查数组中是否存在某个值。使用 strict=true 进行类型安全比较。

Parameters

NameTypeDescription
needlestring要搜索的值。
haystackstring要搜索的数组。

Returns

string

Example

php
<?php
echo trim("  hello  ");        // "hello"
echo trim("---hi---", "-");    // "hi"