PHP字符转换函数示例
发布时间:2023-06-30 01:50:30
在PHP中,我们可以使用一些内置的字符转换函数来操作字符串。下面是一些常用的字符转换函数的示例:
1. strtoupper() 函数:将字符串中的字母转换为大写。
$str = "hello world"; echo strtoupper($str); // 输出: HELLO WORLD
2. strtolower() 函数:将字符串中的字母转换为小写。
$str = "Hello World"; echo strtolower($str); // 输出: hello world
3. ucfirst() 函数:将字符串中的 个字母转换为大写。
$str = "hello world"; echo ucfirst($str); // 输出: Hello world
4. ucwords() 函数:将字符串中的每个单词的首字母转换为大写。
$str = "hello world"; echo ucwords($str); // 输出: Hello World
5. str_replace() 函数:将字符串中的某个字符或字符组合替换为指定的字符串。
$str = "hello world";
echo str_replace("world", "PHP", $str); // 输出: hello PHP
6. addslashes() 函数:在字符串中的某些字符前加上反斜杠,以便在数据库等地方使用。
$str = "I'm a student."; echo addslashes($str); // 输出: I\'m a student.
7. stripslashes() 函数:去除字符串中的反斜杠。
$str = "I\'m a student."; echo stripslashes($str); // 输出: I'm a student.
8. htmlspecialchars() 函数:将特殊字符转换为HTML实体。
$str = "<script>alert('Hello');</script>";
echo htmlspecialchars($str); // 输出: <script>alert('Hello');</script>
这些函数示例仅供参考,PHP还有更多的字符转换函数可以根据需求使用。
