欢迎访问宙启技术站
智能推送

PHP字符串函数简介和用法

发布时间:2023-06-22 10:04:58

PHP字符串函数主要用于处理字符串相关的操作,包括获取字符串长度、查找字符串、替换字符串、格式化字符串等。下面就为大家介绍一下常用的PHP字符串函数及简单的用法。

1. strlen函数--获取字符串长度

strlen函数用于获取字符串的长度,语法如下:

strlen(string $string): int

例:

$str = "hello world";

$length = strlen($str);

echo $length;

输出结果为:11

2. strpos函数--查找字符串

strpos函数用于查找字符串中是否包含特定的字符或子串,并返回其 次出现的位置。语法如下:

strpos(string $haystack, string $needle, int $offset = 0): int|bool

例:

$str = "I am a boy";

$pos = strpos($str, "boy");

if ($pos === false) {

    echo "Not found";

} else {

    echo "Found at position " . $pos;

}

输出结果为:Found at position 7

3. str_replace函数--替换字符串

str_replace函数用于替换字符串中的字符或子串,语法如下:

str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null): mixed

例:

$str = "hello world";

$new_str = str_replace("world", "PHP", $str);

echo $new_str;

输出结果为:hello PHP

4. strtoupper函数--字符串转为大写

strtoupper函数用于将字符串中的字母全部转为大写,语法如下:

strtoupper(string $string): string

例:

$str = "hello world";

$new_str = strtoupper($str);

echo $new_str;

输出结果为:HELLO WORLD

5. strtolower函数--字符串转为小写

strtolower函数用于将字符串中的字母全部转为小写,语法如下:

strtolower(string $string): string

例:

$str = "HELLO WORLD";

$new_str = strtolower($str);

echo $new_str;

输出结果为:hello world

6. strrev函数--字符串翻转

strrev函数用于将字符串翻转,语法如下:

strrev(string $string): string

例:

$str = "hello";

$new_str = strrev($str);

echo $new_str;

输出结果为:olleh

7. substr函数--截取字符串

substr函数用于截取字符串的一部分,语法如下:

substr(string $string, int $start, int $length = null): string

例:

$str = "hello world";

$sub_str = substr($str, 6, 5); //从下标为6的位置开始截取5个字符

echo $sub_str;

输出结果为:world

8. trim函数--去除字符串两端的空格

trim函数用于去除字符串两端的空格或其他指定的字符,语法如下:

trim(string $string, string $characters = " \t

\r\0\x0B"): string

例:

$str = "   hello world   ";

$new_str = trim($str);

echo $new_str;

输出结果为:hello world

以上就是PHP字符串函数的简介和用法,希望对大家有所帮助。