内置函数
PHP 提供了大量的内置函数,这些函数可以帮助我们快速完成各种任务,而无需重新编写代码。掌握常用的内置函数将大大提高你的开发效率。
什么是内置函数
内置函数是 PHP 已经预先定义好的函数,我们可以直接调用它们来完成特定的功能。这些函数涵盖了字符串处理、数学计算、数组操作、文件处理、日期时间处理等各个方面。
字符串处理函数
字符串处理是 Web 开发中最常见的任务之一。PHP 提供了丰富的字符串处理函数。
1. 字符串长度计算
<?php
// strlen() - 计算字符串的长度(字节数)
$text = "Hello World";
$length = strlen($text);
echo $length; // 输出:11
// 中文字符要注意,一个中文字符通常占用3个字节(UTF-8编码)
$chinese = "你好世界";
$chinese_length = strlen($chinese);
echo $chinese_length; // 输出:12(4个中文字符×3字节)
// 如果要计算中文字符数量,可以使用 mb_strlen()
$chinese_count = mb_strlen($chinese, 'UTF-8');
echo $chinese_count; // 输出:4
?>
2. 字符串大小写转换
<?php
// strtolower() - 将字符串转换为小写
$text = "Hello WORLD";
$lower = strtolower($text);
echo $lower; // 输出:hello world
// strtoupper() - 将字符串转换为大写
$upper = strtoupper($text);
echo $upper; // 输出:HELLO WORLD
// ucfirst() - 将字符串的首字母转换为大写
$sentence = "hello php";
$capitalized = ucfirst($sentence);
echo $capitalized; // 输出:Hello php
// ucwords() - 将字符串中每个单词的首字母转换为大写
$title = "welcome to php world";
$title_case = ucwords($title);
echo $title_case; // 输出:Welcome To Php World
?>
3. 字符串查找和替换
<?php
// strpos() - 查找字符串在另一个字符串中首次出现的位置
$text = "Hello, welcome to the world of PHP";
$position = strpos($text, "world");
echo $position; // 输出:25
// 检查字符串是否存在
if (strpos($text, "PHP") !== false) {
echo "找到了PHP!";
}
// str_replace() - 字符串替换
$sentence = "I love apples, apples are delicious!";
$new_sentence = str_replace("apples", "oranges", $sentence);
echo $new_sentence; // 输出:I love oranges, oranges are delicious!
// 替换多个值
$text = "The quick brown fox jumps over the lazy dog";
$replacements = array(
"quick" => "slow",
"brown" => "white",
"fox" => "rabbit"
);
$new_text = str_replace(array_keys($replacements), array_values($replacements), $text);
echo $new_text; // 输出:The slow white rabbit jumps over the lazy dog
?>
4. 字符串截取和分割
<?php
// substr() - 截取字符串
$text = "Hello, World!";
$substring = substr($text, 0, 5);
echo $substring; // 输出:Hello
// 从指定位置截取到末尾
$substring2 = substr($text, 7);
echo $substring2; // 输出:World!
// 负数表示从末尾开始
$last5 = substr($text, -5);
echo $last5; // 输出:orld!
// explode() - 将字符串分割成数组
$fruits = "apple,banana,orange,grape";
$fruit_array = explode(",", $fruits);
print_r($fruit_array);
// 输出:Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
// implode() - 将数组连接成字符串
$array = array('Hello', 'World', 'PHP');
$string = implode(" ", $array);
echo $string; // 输出:Hello World PHP
// 使用不同的分隔符
$string2 = implode("-", $array);
echo $string2; // 输出:Hello-World-PHP
?>
5. 字符串清理和格式化
<?php
// trim() - 去除字符串两端的空白字符
$text = " Hello World ";
$cleaned = trim($text);
echo $cleaned; // 输出:Hello World
// ltrim() - 去除左端空白
$left_trimmed = ltrim($text);
// rtrim() - 去除右端空白
$right_trimmed = rtrim($text);
// strip_tags() - 去除 HTML 和 PHP 标签
$html = "<p>Hello <b>World</b>!</p>";
$plain_text = strip_tags($html);
echo $plain_text; // 输出:Hello World!
// 允许某些标签
$partial_html = strip_tags($html, "<b>");
echo $partial_html; // 输出:Hello <b>World</b>!
// htmlspecialchars() - 将特殊字符转换为 HTML 实体
$user_input = '<script>alert("XSS Attack");</script>';
$safe_output = htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
echo $safe_output;
// 输出:<script>alert("XSS Attack");</script>
?>
6. 字符串格式化
<?php
// printf() - 格式化输出字符串
$name = "张三";
$age = 25;
$height = 1.75;
printf("姓名:%s,年龄:%d岁,身高:%.2f米", $name, $age, $height);
// 输出:姓名:张三,年龄:25岁,身高:1.75米
// sprintf() - 返回格式化的字符串
$formatted = sprintf("产品:%s,价格:¥%.2f", "iPhone", 5999.00);
echo $formatted; // 输出:产品:iPhone,价格:¥5999.00
// number_format() - 格式化数字
$price = 1234567.89;
$formatted_price = number_format($price, 2, '.', ',');
echo $formatted_price; // 输出:1,234,567.89
// str_pad() - 填充字符串到指定长度
$product = "苹果";
$padded = str_pad($product, 10, " ", STR_PAD_RIGHT);
echo $padded; // 输出:"苹果 "(后面有8个空格)
?>
数组函数
数组是 PHP 中最重要的数据结构之一,PHP 提供了大量的数组操作函数。
1. 数组基本操作
<?php
// count() - 计算数组元素数量
$fruits = array("apple", "banana", "orange");
$element_count = count($fruits);
echo $element_count; // 输出:3
// is_array() - 检查变量是否为数组
$not_array = "hello";
if (is_array($fruits)) {
echo "fruits 是一个数组";
}
// in_array() - 检查值是否在数组中
if (in_array("apple", $fruits)) {
echo "找到了苹果!";
}
// array_key_exists() - 检查键是否存在
$person = array(
"name" => "张三",
"age" => 25,
"city" => "北京"
);
if (array_key_exists("age", $person)) {
echo "存在 age 键";
}
// array_keys() - 获取数组的所有键
$keys = array_keys($person);
print_r($keys); // 输出:Array ( [0] => name [1] => age [2] => city )
// array_values() - 获取数组的所有值
$values = array_values($person);
print_r($values); // 输出:Array ( [0] => 张三 [1] => 25 [2] => 北京 )
?>
2. 数组添加和删除
<?php
// array_push() - 向数组末尾添加一个或多个元素
$numbers = array(1, 2, 3);
array_push($numbers, 4, 5);
print_r($numbers); // 输出:Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
// array_pop() - 删除数组末尾的元素
$last = array_pop($numbers);
echo $last; // 输出:5
// array_shift() - 删除数组开头的元素
$first = array_shift($numbers);
echo $first; // 输出:1
// array_unshift() - 在数组开头添加一个或多个元素
array_unshift($numbers, 0);
print_r($numbers); // 输出:Array ( [0] => 0 [1] => 2 [2] => 3 [3] => 4 )
// unset() - 删除指定的数组元素
$colors = array("red", "green", "blue", "yellow");
unset($colors[1]); // 删除 "green"
print_r($colors); // 输出:Array ( [0] => red [2] => blue [3] => yellow )
?>
3. 数组排序
<?php
// sort() - 对数组进行升序排序(索引重新分配)
$numbers = array(4, 2, 8, 1, 5);
sort($numbers);
print_r($numbers); // 输出:Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 8 )
// rsort() - 对数组进行降序排序
rsort($numbers);
print_r($numbers); // 输出:Array ( [0] => 8 [1] => 5 [2] => 4 [3] => 2 [4] => 1 )
// asort() - 对关联数组按值进行升序排序(保持键值关系)
$person_ages = array(
"张三" => 25,
"李四" => 30,
"王五" => 20
);
asort($person_ages);
print_r($person_ages);
// 输出:Array ( [王五] => 20 [张三] => 25 [李四] => 30 )
// ksort() - 对关联数组按键进行升序排序
ksort($person_ages);
print_r($person_ages);
// 输出:Array ( [张三] => 25 [李四] => 30 [王五] => 20 )
// array_reverse() - 反转数组
$reversed = array_reverse($numbers);
print_r($reversed);
?>
4. 数组合并与分割
<?php
// array_merge() - 合并一个或多个数组
$array1 = array("red", "green");
$array2 = array("blue", "yellow");
$merged = array_merge($array1, $array2);
print_r($merged); // 输出:Array ( [0] => red [1] => green [2] => blue [3] => yellow )
// 合并关联数组
$person1 = array("name" => "张三", "age" => 25);
$person2 = array("city" => "北京", "job" => "工程师");
$merged_person = array_merge($person1, $person2);
print_r($merged_person);
// 输出:Array ( [name] => 张三 [age] => 25 [city] => 北京 [job] => 工程师 )
// array_slice() - 从数组中取出一段
$colors = array("red", "green", "blue", "yellow", "purple");
$slice = array_slice($colors, 1, 3);
print_r($slice); // 输出:Array ( [0] => green [1] => blue [2] => yellow )
// array_chunk() - 将数组分割成多个块
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8);
$chunks = array_chunk($numbers, 3);
print_r($chunks);
/*
输出:
Array (
[0] => Array ( [0] => 1 [1] => 2 [2] => 3 )
[1] => Array ( [0] => 4 [1] => 5 [2] => 6 )
[2] => Array ( [0] => 7 [1] => 8 )
)
*/
?>
5. 数组搜索和过滤
<?php
// array_search() - 在数组中搜索值,返回键名
$fruits = array("a" => "apple", "b" => "banana", "c" => "orange");
$key = array_search("orange", $fruits);
echo $key; // 输出:c
// array_filter() - 用回调函数过滤数组中的元素
$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$even_numbers = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
print_r($even_numbers); // 输出:Array ( [1] => 2 [3] => 4 [5] => 6 [7] => 8 [9] => 10 )
// array_map() - 对数组中的每个元素应用回调函数
$squares = array_map(function($num) {
return $num * $num;
}, $numbers);
print_r($squares);
// array_unique() - 移除数组中的重复值
$duplicates = array(1, 2, 2, 3, 4, 4, 5);
$unique = array_unique($duplicates);
print_r($unique); // 输出:Array ( [0] => 1 [1] => 2 [3] => 3 [4] => 4 [6] => 5 )
?>
数学函数
PHP 提供了丰富的数学计算函数。
1. 基础数学运算
<?php
// abs() - 绝对值
echo abs(-5); // 输出:5
// round() - 四舍五入
echo round(3.14159, 2); // 输出:3.14
// ceil() - 向上取整
echo ceil(3.2); // 输出:4
// floor() - 向下取整
echo floor(3.8); // 输出:3
// max() - 最大值
echo max(1, 5, 3, 9, 2); // 输出:9
// min() - 最小值
echo min(1, 5, 3, 9, 2); // 输出:1
// rand() - 生成随机数
echo rand(1, 100); // 输出:1到100之间的随机数
// mt_rand() - 更好的随机数生成器
echo mt_rand(1, 100);
?>
2. 高级数学函数
<?php
// pow() - 幂运算
echo pow(2, 3); // 输出:8(2的3次方)
// sqrt() - 平方根
echo sqrt(16); // 输出:4
// number_format() - 格式化数字
$number = 1234567.8912;
echo number_format($number, 2, '.', ','); // 输出:1,234,567.89
// is_numeric() - 检查变量是否为数字或数字字符串
var_dump(is_numeric("123")); // 输出:bool(true)
var_dump(is_numeric("abc")); // 输出:bool(false)
// base_convert() - 在不同进制之间转换
echo base_convert("FF", 16, 10); // 输出:255(十六进制转十进制)
echo base_convert("10", 10, 2); // 输出:1010(十进制转二进制)
?>
日期和时间函数
处理日期和时间是 Web 开发中的常见需求。
1. 获取当前时间
<?php
// time() - 返回当前的 Unix 时间戳
$timestamp = time();
echo $timestamp; // 输出:当前时间戳
// date() - 格式化本地日期和时间
echo date("Y-m-d H:i:s"); // 输出:2024-01-01 12:30:45
// 常用的日期格式字符
echo date("Y"); // 年份(4位)
echo date("y"); // 年份(2位)
echo date("m"); // 月份(01-12)
echo date("d"); // 日(01-31)
echo date("H"); // 小时(00-23)
echo date("i"); // 分钟(00-59)
echo date("s"); // 秒(00-59)
echo date("l"); // 星期几的完整名称
echo date("F"); // 月份的完整名称
// getdate() - 获取日期/时间信息
$date_info = getdate();
print_r($date_info);
/*
输出:
Array (
[seconds] => 45
[minutes] => 30
[hours] => 12
[mday] => 1
[wday] => 1
[mon] => 1
[year] => 2024
[yday] => 0
[weekday] => Monday
[month] => January
[0] => 1704113445
)
*/
?>
2. 日期时间转换
<?php
// strtotime() - 将英文文本的日期时间描述转换为 Unix 时间戳
$timestamp = strtotime("2024-01-01");
echo $timestamp; // 输出:对应的时间戳
$timestamp2 = strtotime("+1 day"); // 明天
$timestamp3 = strtotime("+1 week"); // 一周后
$timestamp4 = strtotime("next Monday"); // 下周一
// mktime() - 取得一个日期的 Unix 时间戳
$custom_timestamp = mktime(12, 30, 45, 1, 1, 2024); // 2024年1月1日 12:30:45
echo date("Y-m-d H:i:s", $custom_timestamp);
// date_create() 和 date_format() - 使用 DateTime 类
$date = date_create("2024-01-01 12:30:45");
echo date_format($date, "Y-m-d H:i:s");
// 计算日期差
$date1 = date_create("2024-01-01");
$date2 = date_create("2024-01-31");
$diff = date_diff($date1, $date2);
echo $diff->days; // 输出:30(天数差)
?>
3. 时区处理
<?php
// 设置时区
date_default_timezone_set("Asia/Shanghai");
// 获取所有可用的时区
// $timezones = DateTimeZone::listIdentifiers();
// print_r($timezones);
// 创建带时区的 DateTime 对象
$date = new DateTime("now", new DateTimeZone("Asia/Shanghai"));
echo $date->format("Y-m-d H:i:s");
// 转换时区
$date->setTimezone(new DateTimeZone("America/New_York"));
echo $date->format("Y-m-d H:i:s");
?>
文件系统函数
文件操作是 Web 开发中的重要功能。
1. 文件基本操作
<?php
// file_exists() - 检查文件或目录是否存在
$filename = "test.txt";
if (file_exists($filename)) {
echo "文件存在";
} else {
echo "文件不存在";
}
// is_file() - 判断是否为文件
if (is_file($filename)) {
echo "这是一个文件";
}
// is_dir() - 判断是否为目录
if (is_dir("images")) {
echo "这是一个目录";
}
// filesize() - 获取文件大小
$filesize = filesize($filename);
echo "文件大小:" . $filesize . " 字节";
// filemtime() - 获取文件修改时间
$mod_time = filemtime($filename);
echo "最后修改时间:" . date("Y-m-d H:i:s", $mod_time);
?>
2. 文件读写
<?php
// file_get_contents() - 读取整个文件
$content = file_get_contents("test.txt");
echo $content;
// file_put_contents() - 写入文件
$data = "Hello, PHP!";
file_put_contents("output.txt", $data);
// 追加内容
file_put_contents("output.txt", "\nMore content", FILE_APPEND);
// fopen(), fread(), fwrite(), fclose() - 传统文件操作
$handle = fopen("test.txt", "r"); // 只读模式
if ($handle) {
$content = fread($handle, filesize("test.txt"));
fclose($handle);
echo $content;
}
// 写入文件
$handle = fopen("write.txt", "w"); // 写入模式
if ($handle) {
fwrite($handle, "新的内容");
fclose($handle);
}
// readfile() - 读取文件并输出到浏览器
// readfile("test.txt");
// fgets() - 逐行读取文件
$handle = fopen("test.txt", "r");
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
?>
3. 目录操作
<?php
// mkdir() - 创建目录
if (!file_exists("new_folder")) {
mkdir("new_folder", 0777, true); // 0777是权限,true表示递归创建
}
// rmdir() - 删除空目录
// rmdir("empty_folder");
// scandir() - 列出目录内容
$files = scandir(".");
print_r($files);
// opendir(), readdir(), closedir() - 传统目录遍历
$handle = opendir(".");
if ($handle) {
while (($file = readdir($handle)) !== false) {
if ($file != "." && $file != "..") {
echo $file . "\n";
}
}
closedir($handle);
}
// rename() - 重命名文件或目录
rename("old_name.txt", "new_name.txt");
// copy() - 复制文件
copy("source.txt", "backup.txt");
// unlink() - 删除文件
// unlink("file_to_delete.txt");
?>
常用的实用函数
1. 变量处理函数
<?php
// isset() - 检查变量是否已设置并且非 null
$name = "张三";
if (isset($name)) {
echo "变量已设置";
}
// empty() - 检查变量是否为空
$var = "";
if (empty($var)) {
echo "变量为空";
}
// is_null() - 检查变量是否为 null
$var = null;
if (is_null($var)) {
echo "变量为 null";
}
// unset() - 销毁变量
$test = "hello";
unset($test); // $test 现在未定义
// gettype() - 获取变量的类型
$num = 123;
echo gettype($num); // 输出:integer
// settype() - 设置变量的类型
$str = "123";
settype($str, "integer");
echo gettype($str); // 输出:integer
// var_dump() - 打印变量的类型和值
$array = array("apple", "banana", "orange");
var_dump($array);
// print_r() - 打印变量的易读信息
print_r($array);
?>
2. 输入输出函数
<?php
// echo - 输出一个或多个字符串
echo "Hello World";
// print - 输出一个字符串(返回值始终为1)
print "Hello PHP";
// var_export() - 输出或返回一个变量的字符串表示
$array = array(1, 2, 3);
$representation = var_export($array, true);
echo $representation;
// die() 或 exit() - 输出消息并终止脚本
if ($error_occurred) {
die("发生错误,程序终止");
}
// printf() - 格式化输出
$name = "张三";
$age = 25;
printf("姓名:%s,年龄:%d岁", $name, $age);
?>
3. HTTP 相关函数
<?php
// header() - 发送原始 HTTP 头
header("Content-Type: text/html; charset=utf-8");
header("Location: https://www.example.com"); // 重定向
// setcookie() - 设置 cookie
setcookie("username", "john", time() + 3600, "/"); // 1小时后过期
// $_COOKIE - 访问 cookie 值
if (isset($_COOKIE["username"])) {
echo "欢迎回来," . $_COOKIE["username"];
}
// $_GET - 获取 GET 请求参数
if (isset($_GET["id"])) {
$id = $_GET["id"];
echo "商品ID:" . $id;
}
// $_POST - 获取 POST 请求参数
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
}
// $_REQUEST - 包含 $_GET、$_POST 和 $_COOKIE 的内容
$name = $_REQUEST["name"]; // 可以从任何请求方法获取
// $_SERVER - 服务器和执行环境信息
echo "当前脚本路径:" . $_SERVER["PHP_SELF"];
echo "服务器IP地址:" . $_SERVER["SERVER_ADDR"];
echo "客户端IP地址:" . $_SERVER["REMOTE_ADDR"];
echo "请求方法:" . $_SERVER["REQUEST_METHOD"];
?>
4. 会话处理函数
<?php
// session_start() - 启动会话
session_start();
// $_SESSION - 访问会话变量
$_SESSION["username"] = "张三";
$_SESSION["login_time"] = time();
// session_destroy() - 销毁会话
// session_destroy();
// session_unset() - 释放所有会话变量
// session_unset();
// 获取会话ID
$session_id = session_id();
echo "会话ID:" . $session_id;
?>
函数使用技巧
1. 函数参数传递
<?php
// 引用传递(在变量前加 &)
function add_prefix(&$string, $prefix) {
$string = $prefix . $string;
}
$text = "World";
add_prefix($text, "Hello ");
echo $text; // 输出:Hello World
// 默认参数值
function greet($name, $greeting = "Hello") {
return $greeting . ", " . $name;
}
echo greet("张三"); // 输出:Hello, 张三
echo greet("李四", "Hi"); // 输出:Hi, 李四
// 可变参数数量
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3); // 输出:6
echo sum(1, 2, 3, 4, 5); // 输出:15
?>
2. 回调函数
<?php
// 使用匿名函数作为回调
$numbers = array(1, 2, 3, 4, 5);
$even_numbers = array_filter($numbers, function($num) {
return $num % 2 == 0;
});
print_r($even_numbers);
// 使用可调用类型
class Calculator {
public function multiply($x, $y) {
return $x * $y;
}
}
$calc = new Calculator();
$result = array_map([$calc, 'multiply'], [1, 2, 3], [4, 5, 6]);
print_r($result); // 输出:Array ( [0] => 4 [1] => 10 [2] => 18 )
?>
3. 函数存在性检查
<?php
// function_exists() - 检查函数是否存在
if (function_exists('curl_init')) {
echo "cURL 扩展已安装";
} else {
echo "cURL 扩展未安装";
}
// method_exists() - 检查对象方法是否存在
class MyClass {
public function test() {
return "test method";
}
}
$obj = new MyClass();
if (method_exists($obj, 'test')) {
echo "test 方法存在";
}
// class_exists() - 检查类是否存在
if (class_exists('DateTime')) {
$date = new DateTime();
echo $date->format('Y-m-d');
}
?>
最佳实践
1. 使用内置函数的优点
- 性能优化:内置函数通常是用 C 语言实现的,执行速度更快
- 代码简洁:避免重复造轮子,代码更加简洁易读
- 标准化:使用标准函数,代码更容易维护
- 安全性:内置函数通常经过充分测试,更安全可靠
2. 选择合适的函数
<?php
// 选择合适的字符串函数
$text = " Hello World ";
// 推荐:使用 trim()
$clean = trim($text);
// 不推荐:手动处理
$clean = preg_replace('/^\s+|\s+$/', '', $text);
// 选择合适的数组函数
$numbers = array(1, 2, 3, 4, 5);
// 推荐:使用 array_sum()
$total = array_sum($numbers);
// 不推荐:手动循环
$total = 0;
foreach ($numbers as $num) {
$total += $num;
}
?>
3. 函数链式调用
<?php
// 可以将多个函数调用链接起来
$text = " HELLO WORLD ";
// 链式调用
$result = trim(strtolower($text));
echo $result; // 输出:hello world
// 组合使用多个函数
$date = "2024-01-01";
$formatted = date("Y年m月d日", strtotime($date));
echo $formatted; // 输出:2024年01月01日
?>
4. 错误处理
<?php
// 使用 @ 抑制错误(谨慎使用)
$file_content = @file_get_contents("nonexistent.txt");
// 检查函数返回值
$content = file_get_contents("test.txt");
if ($content === false) {
echo "读取文件失败";
} else {
echo $content;
}
// 使用异常处理
try {
$date = new DateTime("invalid date");
} catch (Exception $e) {
echo "日期格式错误:" . $e->getMessage();
}
?>
总结
PHP 的内置函数是强大的工具箱,掌握常用的内置函数可以大大提高开发效率。记住以下几点:
- 多查阅文档:PHP 官方文档提供了详细的函数说明和示例
- 注重实践:通过实际编程加深对函数的理解
- 性能考虑:优先使用内置函数而不是自己实现
- 安全第一:处理用户输入时要注意安全过滤
- 代码可读性:选择最合适、最易读的函数
随着你的 PHP 学习深入,你会越来越熟悉这些内置函数,并能够灵活运用它们解决各种编程问题。