10个必备的PHP函数及其示例
1. strlen() – 返回字符串长度
$hello = "hello";
echo strlen($hello); //输出5
2. strpos() – 返回字符串中给定字符或子字符串的 个出现位置
$hello = "hello world";
echo strpos($hello, "world"); //输出6
3. str_replace() – 在字符串中替换文字
$hello = "hello world";
echo str_replace("world", "php", $hello); //输出"hello php"
4. explode() – 将字符串转换为数组
$hello = "hello world";
$arr = explode(' ', $hello);
echo $arr[0]; //输出"hello"
5. implode() – 将数组转换为字符串
$arr = array('hello', 'world');
$hello = implode(' ', $arr);
echo $hello; //输出"hello world"
6. strtolower() – 将字符串转换为小写字母
$hello = "Hello World";
echo strtolower($hello); //输出"hello world"
7. strtoupper() – 将字符串转换为大写字母
$hello = "Hello World";
echo strtoupper($hello); //输出"HELLO WORLD"
8. ucwords() – 将每个单词的首字母转换为大写字母
$hello = "hello world";
echo ucwords($hello); //输出"Hello World"
9. filter_var() – 过滤用户输入的数据
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Email is valid";
} else {
echo "Email is not valid";
}
10. intval() – 将字符串转换为整数
$num = "123";
$num = intval($num);
echo $num; //输出123
