PHP 字符串处理技巧
PHP 字符串处理常用技巧
字符串处理是 PHP 开发最常用的操作,掌握这些函数,写代码效率翻倍。
1. 截取字符串
// 截取前 5 个字符
substr("hello world", 0, 5); // hello
// 截取从第 6 个开始到结尾
substr("hello world", 6); // world
// 中文字符串截取(用 mb_)
mb_substr("你好世界", 0, 2, "UTF-8"); // 你好
注意:中文要用 mb_substr,不能用 substr,否则会乱码。
2. 替换字符串
// str_replace(替换所有)
str_replace("world", "PHP", "hello world"); // hello PHP
// str_ireplace(不区分大小写)
str_ireplace("WORLD", "PHP", "hello world");
// preg_replace(正则替换)
preg_replace("/\d/", "", "abc123def"); // abcdef
3. 查找字符串
// 查找位置(找不到返回 false)
strpos("hello world", "world"); // 6
// 查找最后出现位置
strrpos("hello world hello", "hello"); // 12
// 判断是否包含(PHP 8+)
str_contains("hello world", "world"); // true
// 判断开头
str_starts_with("hello world", "hello"); // true
// 判断结尾
str_ends_with("hello world", "world"); // true
4. 格式化字符串
// 去除首尾空格
trim(" hello "); // hello
// 只去左边/右边
ltrim(" hello"); // hello
rtrim("hello "); // hello
// 转小写/大写
strtolower("Hello"); // hello
strtoupper("hello"); // HELLO
// 首字母大写
ucfirst("hello"); // Hello
// 每个单词首字母大写
ucwords("hello world"); // Hello World
5. 字符串和数组转换
// 字符串转数组
explode(",", "a,b,c"); // ["a","b","c"]
// 数组转字符串
implode(",", ["a","b","c"]); // a,b,c
// 重复字符串
str_repeat("ab", 3); // ababab
// 字符串长度
strlen("hello"); // 5
mb_strlen("你好", "UTF-8"); // 2
6. 常用技巧
// 生成随机字符串
substr(md5(time()), 0, 8);
// 脱敏手机号
substr_replace("13812345678", "****", 3, 4); // 138****5678
// 截取摘要(带省略号)
mb_strlen($text) > 10 ? mb_substr($text, 0, 10) . "..." : $text;
// 清除 HTML 标签
strip_tags("<p>hello</p>"); // hello
总结
PHP 字符串处理核心函数:
- 截取:substr / mb_substr
- 替换:str_replace / preg_replace
- 查找:strpos / str_contains
- 格式化:trim / strtolower / ucwords
- 转换:explode / implode
记住这些,日常开发基本够用了。
PHP 数组操作技巧
PHP 数组操作技巧
数组是 PHP 最常用的数据结构,掌握这些技巧,写代码效率翻倍。
1. 数组合并
// 索引数组合并
$arr1 = [1, 2];
$arr2 = [3, 4];
$result = array_merge($arr1, $arr2); // [1,2,3,4]
// 关联数组合并,后面覆盖前面
$arr1 = ['a' => 1, 'b' => 2];
$arr2 = ['b' => 3, 'c' => 4];
$result = array_merge($arr1, $arr2); // ['a'=>1, 'b'=>3, 'c'=>4]
2. 数组去重
// 一维数组去重
$arr = [1, 2, 2, 3, 3, 3];
$result = array_unique($arr); // [1,2,3]
// 二维数组按字段去重
$users = [
['id' => 1, 'name' => '张三'],
['id' => 2, 'name' => '李四'],
['id' => 1, 'name' => '张三'],
];
$ids = array_column($users, 'id');
$unique = array_unique($ids);
3. 数组排序
// 升序
sort($arr);
// 降序
rsort($arr);
// 按键排序
ksort($arr);
// 按值排序,保留键
asort($arr);
4. 数组过滤
// 过滤空值
$arr = [1, 0, '', null, 'a'];
$result = array_filter($arr); // [1, 'a']
// 自定义过滤
$result = array_filter($arr, function($value) {
return $value > 2;
});
5. 数组取值
// 取某一列
$names = array_column($users, 'name');
// 取交集
$arr1 = [1, 2, 3];
$arr2 = [2, 3, 4];
$result = array_intersect($arr1, $arr2); // [2,3]
// 取差集
$result = array_diff($arr1, $arr2); // [1]
6. 常用技巧
// 判断键是否存在
isset($arr['key']);
array_key_exists('key', $arr);
// 随机取一个
$value = array_rand($arr);
// 打乱数组
shuffle($arr);
// 数组合并成字符串
$str = implode(',', $arr);
// 字符串转数组
$arr = explode(',', $str);
总结
PHP 数组函数非常丰富,常用的就这些:合并、去重、排序、过滤、取值。把这些记熟,日常开发基本够用了。