PHP提取文章中的base64图片并保存
$content = '<p>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAdCAYAAACqhkzFAAABIklEQVRIDdXUMUvDUBDA8X4mZ7+E4O4kTq4OgquDo6Ojm3PBjyAUQQWjaIvWtoioi6EhtZqXv1yh8gS9u5S3GAh58C6/XN4d1+JkCff90oY6oF0tN3a3C9VYs2Z7PrCzDMWViUmAD3zYh/CeEMzPXJgvw9st+MwTgo+HUFcJwbeOG7N/Wapb9hOC2QZMnxOC3W1XM8df1PuwtwNVEceb6/8OJi/K+QpMhua5xQH6GcqszE/jeHNtg09H5lCNv2KD0otJh8NsuN7ESahrO0M5x9EBhA8Vmm/6QKl20Zu/oz59oGTZ34NQqphs+kFBX4/NijcDL1ah6KpZNgMly2wdyvs/0eagoNebMBn8ii4GCnq5BuMMqH/Ai4OCStNLocL0G/0CVUXjdj/fHwgAAAAASUVORK5CYII=" alt="" />
</p>';
//规则
$pattern = '/data:image\/(\w+);base64,(.*?)(?="|$)/i';
/*
* 正则获取
* preg_match 只获取第一个匹配
* preg_match_all 获取所有匹配
*/
preg_match($pattern, $content, $matches);
//var_dump($matches);
//结果
$matches[0] = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAdCAYAAACqhkzFAAABIklEQVRIDdXUMUvDUBDA8X4mZ7+E4O4kTq4OgquDo6Ojm3PBjyAUQQWjaIvWtoioi6EhtZqXv1yh8gS9u5S3GAh58C6/XN4d1+JkCff90oY6oF0tN3a3C9VYs2Z7PrCzDMWViUmAD3zYh/CeEMzPXJgvw9st+MwTgo+HUFcJwbeOG7N/Wapb9hOC2QZMnxOC3W1XM8df1PuwtwNVEceb6/8OJi/K+QpMhua5xQH6GcqszE/jeHNtg09H5lCNv2KD0otJh8NsuN7ESahrO0M5x9EBhA8Vmm/6QKl20Zu/oz59oGTZ34NQqphs+kFBX4/NijcDL1ah6KpZNgMly2wdyvs/0eagoNebMBn8ii4GCnq5BuMMqH/Ai4OCStNLocL0G/0CVUXjdj/fHwgAAAAASUVORK5CYII=';
$matches[1] = 'png';
$matches[2] = 'iVBORw0KGgoAAAANSUhEUgAAABQAAAAdCAYAAACqhkzFAAABIklEQVRIDdXUMUvDUBDA8X4mZ7+E4O4kTq4OgquDo6Ojm3PBjyAUQQWjaIvWtoioi6EhtZqXv1yh8gS9u5S3GAh58C6/XN4d1+JkCff90oY6oF0tN3a3C9VYs2Z7PrCzDMWViUmAD3zYh/CeEMzPXJgvw9st+MwTgo+HUFcJwbeOG7N/Wapb9hOC2QZMnxOC3W1XM8df1PuwtwNVEceb6/8OJi/K+QpMhua5xQH6GcqszE/jeHNtg09H5lCNv2KD0otJh8NsuN7ESahrO0M5x9EBhA8Vmm/6QKl20Zu/oz59oGTZ34NQqphs+kFBX4/NijcDL1ah6KpZNgMly2wdyvs/0eagoNebMBn8ii4GCnq5BuMMqH/Ai4OCStNLocL0G/0CVUXjdj/fHwgAAAAASUVORK5CYII=';
/*
* 图片大小
* 单位b
*/
$imgLen = strlen($matches[2]);
$fileSize = $imgLen - ($imgLen / 8) * 2;
//保存图片
$fullFileName = './image.png';
file_put_contents($fullFileName, base64_decode($matches[2]))
当检测内容比较大时,会检测失败,
原因:PHP对正则表达式匹配长度是用限制的,用phpinfo可以看到如下
pcre.backtrack_limit 100000 100000
pcre.recursion_limit 100000 100000
发现只有100K,只要在php.ini上做相应设置就行了(或者改变这两个值的大小)
pcre.backtrack_limit=-1
pcre.recursion_limit=-1
附说明:
[Pcre]
;Perl兼容正则表达式模块
pcre.backtrack_limit = 100000
; PCRE的最大回溯(backtracking)步数。
pcre.recursion_limit = 100000
; PCRE的最大递归(recursion)深度。
; 如果你将该值设的非常高,将可能耗尽进程的栈空间,导致PHP崩溃。
原文地址:https://blog.csdn.net/jugtba/article/details/136351261
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!