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

10个php字符串操作函数,让你的文本处理更高效

发布时间:2023-06-09 04:47:19

1. strlen()

该函数返回给定字符串的长度。它使用以下语法:

int strlen ( string $string )

示例:

$str = "Hello world!";

echo strlen($str); // 输出:12

2. strpos()

该函数用于查找字符串中子串的位置。它使用以下语法:

int strpos ( string $haystack , mixed $needle [, int $offset = 0] )

示例:

$str = "Hello world!";

echo strpos($str, "world"); // 输出:6

3. substr()

该函数返回由给定字符串的子字符串组成的值。它使用以下语法:

string substr ( string $string , int $start [, int $length ] )

示例:

$str = "Hello world!";

echo substr($str, 0, 5); // 输出:Hello

4. str_replace()

该函数用于替换字符串中的文本。它使用以下语法:

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

示例:

$str = "Hello world!";

echo str_replace("world", "PHP", $str); // 输出:Hello PHP!

5. trim()

该函数用于提取字符串中空格。它使用以下语法:

string trim ( string $str [, string $characters_mask = " \t

\r\0\x0B" ] )

示例:

$str = "   Hello world!   ";

echo trim($str); // 输出:Hello world!

6. strtoupper()

该函数用于将字符串转换为大写。它使用以下语法:

string strtoupper ( string $string )

示例:

$str = "Hello world!";

echo strtoupper($str); // 输出:HELLO WORLD!

7. strtolower()

该函数用于将字符串转换为小写。它使用以下语法:

string strtolower ( string $string )

示例:

$str = "Hello world!";

echo strtolower($str); // 输出:hello world!

8. htmlspecialchars()

该函数将特殊字符转换为相应的 HTML 实体。它使用以下语法:

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = TRUE ]]] )

示例:

$str = "Hello & world!";

echo htmlspecialchars($str); // 输出:Hello & world!

9. implode()

该函数将数组转换为单个字符串。它使用以下语法:

string implode ( string $glue , array $pieces )

示例:

$array = array('Hello', 'world!');

echo implode(" ", $array); // 输出:Hello world!

10. explode()

该函数将字符串分割成数组。它使用以下语法:

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

示例:

$str = "Hello,world!";

print_r(explode(",", $str)); // 输出:Array ( [0] => Hello [1] => world! )