PHP常用函数:substr、str_replace和strpos的使用方法详解
substr、str_replace和strpos是PHP常用的字符串处理函数。下面我们来详细了解一下它们的使用方法。
substr函数
substr函数用于截取字符串,参数如下:
substr(string $string, int $start, ?int $length = null): string
$string:待截取的源字符串;
$start:截取的起始位置。若为正数,则从字符串左侧开始数(从0开始),若为负数,则从字符串右侧开始数(从-1开始);
$length:可选参数。截取的字符个数。若为正数,则从$start开始截取指定长度字符,若为负数,则从$string最右边的字符开始向左数指定长度个字符;若为null,则截取到$string末尾。
例如:
$str = "Hello World!";
echo substr($str, 0, 5); // 输出 "Hello"
echo substr($str, -6); // 输出 "World!"
echo substr($str, 6, -1); // 输出 "o World"
str_replace函数
str_replace函数用于替换字符串中指定的内容,参数如下:
str_replace(mixed $search, mixed $replace, mixed $subject, ?int &$count = null): mixed
$search:待替换的字符串或数组;
$replace:替换后的字符串或数组。若$search和$replace的元素数量不相同,则多余的元素会被舍弃,若$replace元素不足,则用空字符替代;
$subject:待替换的源字符串或数组;
$count:可选参数。替换的次数。若为null,则替换所有匹配的项。
例如:
$str = "Hello World!";
echo str_replace("World", "PHP", $str); // 输出 "Hello PHP!"
$arr = ["apple", "banana", "orange"];
echo str_replace(["apple", "orange"], "pear", $arr); // 输出 ["pear", "banana", "pear"]
strpos函数
strpos函数用于查找字符串中是否包含指定的子串,参数如下:
strpos(string $haystack, mixed $needle, ?int $offset = 0): int|false
$haystack:待查找的源字符串;
$needle:待查找的子串;
$offset:可选参数。查找的起始位置。若省略,则从$string的开头开始查找;若为负数,则从$string结尾的相应字符开始查找。
若找到匹配的子串,则返回它在$haystack中的位置(从0开始计数);若未找到,则返回false。
例如:
$str = "Hello World!";
echo strpos($str, "World"); // 输出 6
echo strpos($str, "java"); // 输出 false
以上是substr、str_replace和strpos的使用方法,这些函数可以帮助我们在PHP中更方便地处理字符串。
