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

常用PHP字符串函数整理及用例

发布时间:2023-07-02 15:35:22

PHP字符串函数是编写PHP程序时常用的函数之一,用于处理和操作字符串。下面整理了一些常用的PHP字符串函数,并且给出了相应的用例。

1. strlen() 函数返回字符串的长度。

$str = "Hello World!";
$len = strlen($str); // 返回12

2. strpos() 函数查找字符串中是否包含另一个字符串,并返回 次出现的位置。

$str = "Hello World!";
$pos = strpos($str, "World"); // 返回6

3. strrpos() 函数查找字符串中最后一次出现另一个字符串的位置。

$str = "Hello World!";
$pos = strrpos($str, "o"); // 返回7

4. substr() 函数返回字符串的一部分。

$str = "Hello World!";
$sub = substr($str, 6, 5); // 返回"World"

5. str_replace() 函数替换字符串中的指定内容。

$str = "Hello World!";
$new_str = str_replace("World", "PHP", $str); // 返回"Hello PHP!"

6. strtolower() 函数将字符串转换为小写。

$str = "Hello World!";
$new_str = strtolower($str); // 返回"hello world!"

7. strtoupper() 函数将字符串转换为大写。

$str = "Hello World!";
$new_str = strtoupper($str); // 返回"HELLO WORLD!"

8. trim() 函数去除字符串两边的空格。

$str = "  Hello World!  ";
$new_str = trim($str); // 返回"Hello World!"

9. explode() 函数将字符串拆分为数组。

$str = "Hello,World!";
$arr = explode(",", $str); // 返回["Hello", "World!"]

10. implode() 函数将数组元素连接为字符串。

$arr = ["Hello", "World!"];
$str = implode(",", $arr); // 返回"Hello,World!"

11. sprintf() 函数将字符串格式化为指定的格式。

$name = "John";
$age = 30;
$str = sprintf("My name is %s and I am %d years old.", $name, $age);
// 返回"My name is John and I am 30 years old."

12. strstr() 函数返回一个字符串在另一个字符串中首次出现的部分。

$str = "Hello World!";
$part = strstr($str, "World"); // 返回"World!"

13. nl2br() 函数将字符串中的换行符(

)转换为HTML中的换行符(<br>标签)。

$str = "Hello
World!";
$new_str = nl2br($str); // 返回"Hello<br>World!"

14. addslashes() 函数在字符串中的某些特殊字符前添加反斜杠。

$str = "I'm John!";
$new_str = addslashes($str); // 返回"I\'m John!"

15. htmlspecialchars() 函数将字符串中的特殊字符转换为HTML实体。

$str = "<h1>Hello World!</h1>";
$new_str = htmlspecialchars($str); // 返回"&lt;h1&gt;Hello World!&lt;/h1&gt;"

这些是常用的PHP字符串函数,通过它们可以实现对字符串的各种操作和处理。在实际编写PHP程序时,通常会用到其中的多个函数组合来完成字符串的相关操作。