php正则替换table的实现方法:首页使用php采集table表格数据;然后利用正则把“”等标签删除掉;最后添加对应的替换即可。
本文操作环境:windows7系统、PHP7.1版,DELL G3电脑
php 正则匹配网页html 中的table 把内容转化成数组
在对接京东vop 的时候,在京东返回规格属性的时候,返回的是 html格式的样式,例
$date=' <table cellpadding="0" cellspacing="1" width="100%"border="0" class="Ptable"> <tr> <th class="tdTitle" colspan="2">主体 </th> <tr> <tr> <td class="tdTitle">品牌 </td> <td>好孩子 </td> </tr> <tr> <td class="tdTitle">主材质 </td> <td>PP </td> </tr> <tr> <td class="tdTitle">规格 </td> <td>800mm*445mm*225 </td> </tr> </table>';
如上的表格 ,预览为
立即学习“PHP免费学习笔记(深入)”;
接下来便是进行提取, 提取思路是 利用正则把 先贴代码 用debug 走流程,观察每一步,具体就不详述,放一张最后$table的变量 经过array_pop之后的变量 是 如下 上面的\r\n 是为了区分加的换行, 可以用str_replace 替换 ,另外还有标题也可以替换, 如下 最终效果 推荐学习:《PHP视频教程》
,
等标签先删除掉。
//php采集table表格数据(将HTML表格的每行每列转为数组)
function tdToArray($table) {
$table = preg_replace("'<table[^>]*?>'si","",$table);
$table = preg_replace("'<tr[^>]*?>'si","",$table);
$table = preg_replace("'<td[^>]*?>'si","",$table);
$table = str_replace("</tr>","{tr}",$table);
$table = str_replace("</td>","{td}",$table);
//去掉 HTML 标记
$table = preg_replace("'<[/!]*?[^<>]*?>'si","",$table);
//去掉空白字符
$table = preg_replace("'([rn])[s]+'","",$table);
$table = str_replace(" ","",$table);
$table = str_replace(" ","",$table);
$table = explode('{tr}', $table);
array_pop($table);
foreach ($table as $key=>$tr) { // 自己可添加对应的替换
$td = explode('{td}', $tr);
array_pop($td);
$td_array[] = $td;
}
return $td_array;
}
以上就是php正则替换table怎么实现的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号