六、数组
6.1 数组基础
PHP中的数组实际上是一个有序映射,可以包含整数、字符串、对象等多种类型的值。
<?php
// 创建数组
$fruits = array("苹果", "香蕉", "橙子");
$colors = ["红", "绿", "蓝"]; // PHP 5.4+短数组语法
// 关联数组(键值对)
$person = [
"name" => "张三",
"age" => 25,
"city" => "北京"
];
// 混合数组
$mixed = [
1,
"name" => "张三",
2,
"age" => 25,
3
];
// 访问数组元素
echo $fruits[0]; // 苹果
echo $person["name"]; // 张三
// 添加元素
$fruits[] = "葡萄"; // 自动添加索引
$fruits[10] = "西瓜"; // 指定索引
$person["email"] = "zhang@example.com";
// 修改元素
$fruits[0] = "苹果酱";
// 删除元素
unset($fruits[1]);
unset($person["age"]);
// 数组长度
echo count($fruits);
echo sizeof($fruits);
// 遍历数组
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
foreach ($person as $key => $value) {
echo "{$key}: {$value}<br>";
}
6.2 数组遍历与指针操作
<?php
$arr = ["苹果", "香蕉", "橙子", "葡萄"];
// 获取当前指针指向的元素
echo current($arr); // 苹果
echo key($arr); // 0
// 移动指针
next($arr); // 移动到下一个
echo current($arr); // 香蕉
prev($arr); // 移动到上一个
echo current($arr); // 苹果
end($arr); // 移动到最后一个
echo current($arr); // 葡萄
reset($arr); // 重置到第一个
echo current($arr); // 苹果
// each()(PHP 7.2+已废弃)
// while (list($key, $value) = each($arr)) {
// echo "{$key}: {$value}";
// }
// 推荐使用foreach
foreach ($arr as $key => $value) {
echo "{$key}: {$value}";
}
6.3 常用数组函数
<?php
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$arr3 = ["a" => 1, "b" => 2, "c" => 3];
// 数组操作
array_push($arr1, 4, 5); // 尾部添加元素
array_pop($arr1); // 尾部删除元素
array_unshift($arr1, 0); // 头部添加元素
array_shift($arr1); // 头部删除元素
// 数组合并
$merged = array_merge($arr1, $arr2); // [1,2,3,4,5,6]
$mergedPlus = $arr1 + $arr2; // 联合,左边优先
// 数组切片
$slice = array_slice($arr1, 1, 2); // 从索引1开始取2个
// 数组去重
$duplicates = [1, 2, 2, 3, 3, 3];
$unique = array_unique($duplicates); // [1,2,3]
// 数组排序
sort($arr1); // 升序,重新索引
rsort($arr1); // 降序,重新索引
asort($arr3); // 升序,保持键值关联
arsort($arr3); // 降序,保持键值关联
ksort($arr3); // 按键升序
krsort($arr3); // 按键降序
usort($arr1, function($a, $b) {
return $a <=> $b;
}); // 自定义排序
// 数组键值操作
$keys = array_keys($arr3); // ["a","b","c"]
$values = array_values($arr3); // [1,2,3]
$hasKey = array_key_exists("a", $arr3); // true
$inArray = in_array(2, $arr3); // true
$key = array_search(2, $arr3); // "b"
// 数组映射和过滤
$squared = array_map(function($n) {
return $n * $n;
}, $arr1);
$even = array_filter($arr1, function($n) {
return $n % 2 == 0;
});
// 数组归约
$sum = array_reduce($arr1, function($carry, $item) {
return $carry + $item;
}, 0);
// 数组随机
$random = array_rand($arr1, 2); // 随机取2个键
shuffle($arr1); // 随机打乱
// 检查数组
is_array($arr1); // true
array_is_list($arr1); // 是否为索引数组(PHP 8.1+)
七、字符串处理
7.1 字符串基础
<?php
// 字符串定义
$str1 = '单引号字符串';
$str2 = "双引号字符串";
// 单引号特性:不解析变量和转义字符(除了\'和\\)
$name = "张三";
echo 'Hello, $name'; // Hello, $name
echo 'Hello, \'World\''; // Hello, 'World'
// 双引号特性:解析变量和转义字符
echo "Hello, $name"; // Hello, 张三
echo "换行:\n";
echo "制表符:\t";
echo "回车:\r";
echo "美元符号:\$";
echo "双引号:\"";
// 字符串长度
$str = "Hello";
echo strlen($str); // 5
echo mb_strlen("你好"); // 2(多字节字符需用mb_函数)
// 字符串访问
echo $str[0]; // H
echo $str[-1]; // o(最后一个字符,PHP 7.1+)
$str[0] = "h"; // 修改字符
// 变量解析复杂语法
echo "Hello, {$name}先生";
echo "Hello, ${name}先生";
7.2 常用字符串函数
<?php
$str = "Hello, World!";
$text = " PHP 编程 ";
// 查找和替换
echo strpos($str, "World"); // 7(查找位置)
echo str_contains($str, "Hello"); // true(PHP 8.0+)
echo str_starts_with($str, "Hello"); // true(PHP 8.0+)
echo str_ends_with($str, "!"); // true(PHP 8.0+)
$replaced = str_replace("World", "PHP", $str); // "Hello, PHP!"
$replaced = str_ireplace("hello", "Hi", $str); // 不区分大小写
// 截取
$sub = substr($str, 0, 5); // "Hello"
$sub = substr($str, 7); // "World!"
$sub = substr($str, -6); // "World!"
// 大小写转换
echo strtoupper("hello"); // "HELLO"
echo strtolower("HELLO"); // "hello"
echo ucfirst("hello"); // "Hello"(首字母大写)
echo ucwords("hello world"); // "Hello World"(每个单词首字母大写)
// 去除空白
echo trim($text); // "PHP 编程"(去除两端)
echo ltrim($text); // "PHP 编程 "(去除左侧)
echo rtrim($text); // " PHP 编程"(去除右侧)
echo chop($text); // 同rtrim
// 分割和连接
$arr = explode(", ", $str); // ["Hello", "World!"]
$str = implode(", ", $arr); // "Hello, World!"
$str = join(", ", $arr); // "Hello, World!"
// 格式化
$formatted = sprintf("%d年%02d月%02d日", 2024, 3, 15); // "2024年03月15日"
printf("价格:%.2f", 19.99); // "价格:19.99"
// HTML相关
$html = "<script>alert('XSS')</script>";
echo htmlspecialchars($html); // <script>alert('XSS')</script>
echo strip_tags($html); // 移除HTML标签
// 字符串填充
$padded = str_pad("Hello", 10, "-", STR_PAD_BOTH); // "--Hello---"
// 反转
$reversed = strrev("Hello"); // "olleH"
// 重复
$repeat = str_repeat("Hi", 3); // "HiHiHi"
// 随机字符串
$random = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, 10);
7.3 正则表达式
<?php
// preg_match():匹配一次
$pattern = "/\d{11}/";
$subject = "我的手机号是13812345678";
if (preg_match($pattern, $subject, $matches)) {
echo "找到手机号:" . $matches[0];
}
// preg_match_all():匹配所有
$pattern = "/\d+/";
$subject = "价格:99元,数量:5个";
preg_match_all($pattern, $subject, $matches);
print_r($matches[0]); // ["99", "5"]
// preg_replace():替换
$pattern = "/\s+/";
$replaced = preg_replace($pattern, "-", "Hello World PHP"); // "Hello-World-PHP"
// preg_split():分割
$pattern = "/[\s,]+/";
$result = preg_split($pattern, "Hello,World PHP"); // ["Hello", "World", "PHP"]
// 常用正则表达式
$email = "user@example.com";
if (preg_match("/^[\w\.-]+@[\w\.-]+\.\w+$/", $email)) {
echo "邮箱格式正确";
}
$url = "https://www.example.com";
if (preg_match("/^https?:\/\/[\w\-]+(\.[\w\-]+)+/", $url)) {
echo "URL格式正确";
}
// 中文匹配
$chinese = "你好PHP";
if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $chinese)) {
echo "包含中文";
}
// 手机号匹配
$phone = "13812345678";
if (preg_match("/^1[3-9]\d{9}$/", $phone)) {
echo "手机号格式正确";
}
八、文件与目录操作
8.1 文件操作
<?php
// 读取文件内容
$content = file_get_contents("file.txt");
echo $content;
// 写入文件
file_put_contents("file.txt", "Hello, World!");
// 逐行读取
$lines = file("file.txt"); // 返回数组,每行一个元素
// 打开文件
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
}
fclose($handle);
}
// 文件打开模式
// "r":只读,指针在开头
// "r+":读写,指针在开头
// "w":只写,清空内容,不存在则创建
// "w+":读写,清空内容,不存在则创建
// "a":追加,指针在末尾,不存在则创建
// "a+":读写追加,指针在末尾,不存在则创建
// "x":创建新文件,如果存在则失败
// "b":二进制模式(Windows需要)
// 写入文件
$handle = fopen("file.txt", "w");
fwrite($handle, "Hello");
fputs($handle, " World"); // fwrite别名
fclose($handle);
// 追加内容
file_put_contents("file.txt", "New content", FILE_APPEND);
// 文件信息
echo file_exists("file.txt"); // 是否存在
echo is_file("file.txt"); // 是否为文件
echo is_dir("dir"); // 是否为目录
echo is_readable("file.txt"); // 是否可读
echo is_writable("file.txt"); // 是否可写
echo filesize("file.txt"); // 文件大小
echo filemtime("file.txt"); // 修改时间
echo filectime("file.txt"); // 创建时间
echo fileatime("file.txt"); // 访问时间
// 删除文件
unlink("file.txt");
// 复制文件
copy("source.txt", "destination.txt");
// 重命名/移动文件
rename("old.txt", "new.txt");
// 文件锁定
$handle = fopen("file.txt", "r+");
if (flock($handle, LOCK_EX)) { // 排他锁
fwrite($handle, "Write");
flock($handle, LOCK_UN); // 释放锁
}
fclose($handle);
8.2 目录操作
<?php
// 创建目录
mkdir("new_dir");
mkdir("parent/sub", 0777, true); // 递归创建
// 删除目录
rmdir("empty_dir"); // 只能删除空目录
// 删除非空目录
function deleteDir($dir) {
if (!file_exists($dir)) {
return true;
}
if (!is_dir($dir)) {
return unlink($dir);
}
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if (!deleteDir($dir . DIRECTORY_SEPARATOR . $item)) {
return false;
}
}
return rmdir($dir);
}
// 读取目录内容
$files = scandir("dir");
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo $file . "\n";
}
}
// 使用DirectoryIterator
$iterator = new DirectoryIterator("dir");
foreach ($iterator as $file) {
if ($file->isDot()) continue;
echo $file->getFilename() . "\n";
echo $file->getSize() . "\n";
echo $file->getMTime() . "\n";
}
// 递归遍历目录
$rii = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("dir")
);
foreach ($rii as $file) {
if (!$file->isDir()) {
echo $file->getPathname() . "\n";
}
}
// 获取当前目录
echo getcwd();
chdir("new_dir"); // 改变目录