引言
PHP图片处理
1. 安装GD库
<?php
// 检查GD库是否安装
if (!extension_loaded('gd')) {
echo 'GD库未安装';
exit();
}
?>
2. 创建和操作图片
<?php
// 创建一个新的图片资源
$width = 100;
$height = 30;
$image = imagecreatetruecolor($width, $height);
// 分配颜色
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
// 填充背景
imagefilledrectangle($image, 0, 0, $width-1, $height-1, $white);
// 添加文字
$font_file = './arial.ttf';
imagettftext($image, 20, 0, 10, 20, $black, $font_file, 'Hello World!');
// 输出图片
header('Content-type: image/png');
imagepng($image);
// 释放内存
imagedestroy($image);
?>
3. 图片编辑
<?php
// 裁剪图片
$source = imagecreatefromjpeg('source.jpg');
$destination = imagecreatetruecolor(100, 100);
imagecopyresized($destination, $source, 0, 0, 50, 50, 100, 100, 200, 200);
// 输出裁剪后的图片
header('Content-type: image/jpeg');
imagejpeg($destination);
// 释放内存
imagedestroy($source);
imagedestroy($destination);
?>
正则表达式高效筛选技巧
1. 元字符
正则表达式中,元字符用于匹配特定的字符。以下是一些常用的元字符:
.:匹配除换行符以外的任意字符*:匹配前面的子表达式零次或多次+:匹配前面的子表达式一次或多次?:匹配前面的子表达式零次或一次
2. 分组和引用
分组用于匹配括号内的表达式,并可以引用:
<?php
$pattern = '/(\d{3})-(\d{2})-(\d{2})/';
$subject = '出生日期:1990-01-01';
preg_match($pattern, $subject, $matches);
// 输出:Array ( [0] => 1990-01-01 [1] => 199 [2] => 01 [3] => 01 )
?>
3. 条件匹配
正则表达式可以用于条件匹配,例如:
<?php
$pattern = '/^(1[3-9])\d{9}$/'; // 匹配中国手机号
$subject = '手机号:13812345678';
if (preg_match($pattern, $subject, $matches)) {
echo '手机号格式正确';
} else {
echo '手机号格式错误';
}
?>
4. 捕获组
捕获组用于提取匹配的内容:
<?php
$pattern = '/(\d{4})-(\d{2})-(\d{2})/';
$subject = '日期:2021-01-01';
preg_match($pattern, $subject, $matches);
// 输出:Array ( [0] => 2021-01-01 [1] => 2021 [2] => 01 [3] => 01 )
?>