当前位置: 代码迷 >> PHP >> Php 提取表格内容的正则表达式
  详细解决方案

Php 提取表格内容的正则表达式

热度:8   发布时间:2016-04-28 18:23:27.0
求一个Php 提取表格内容的正则表达式
字符串可能如下:
$s1 = '这里是描述字符(&nbsp;)<table name="optionsTable" cellpadding="0" cellspacing="0" width="100%"><tr><td width="25%">AAAAA </td><td width="25%"> BBBBB </td></tr></table>';

$s2= ’这里是描述字符(&nbsp;)<table name="optionsTable" cellpadding="0" cellspacing="0" width="100%"><tr><td width="50%"><img src="2061.png" style="vertical-align:middle;" /> </td><td width="50%"> <sub>0</sub></td></tr></table>';

希望能把table表格前的字符 :这里是描述字符(&nbsp;)’ 和 td 中间的字符串提取出来
'BBBBB '、'AAAAA'、'<img src="2061.png" style="vertical-align:middle;" />'、'<sub>0</sub>' 
表格td中间内容可能比较杂,尽量考虑各种情况。


不知道描述得清楚么? 各位正则达人请支招!

------解决思路----------------------
$s1 = '这里是描述字符(&nbsp;)<table name="optionsTable" cellpadding="0" cellspacing="0" width="100%"><tr><td width="25%">AAAAA </td><td width="25%"> BBBBB </td></tr></table>';
$s2= '这里是描述字符(&nbsp;)<table name="optionsTable" cellpadding="0" cellspacing="0" width="100%"><tr><td width="50%"><img src="2061.png" style="vertical-align:middle;" /> </td><td width="50%"> <sub>0</sub></td></tr></table>';
//匹配table前面的内容
preg_match_all('/(.+?)<table[^>]+?>/i',$s1,$p1);
echo "<pre>";
print_r($p1[1]);
echo "</pre>";
//匹配td里面的内容
preg_match_all('/<td[^>]+?>(.+?)<\/td>/i',$s2,$m2);
echo "<pre>";
print_r($m2[1]);
echo "</pre>";

//$p1[1]和$m2[1]就是匹配到的内容

------解决思路----------------------

<?php

$s1 = '这里是描述字符(&nbsp;)<table name="optionsTable" cellpadding="0" cellspacing="0" width="100%"><tr><td width="25%">AAAAA </td><td width="25%"> BBBBB </td></tr></table>';

$s2 = '这里是描述字符(&nbsp;)<table name = "optionsTable" cellpadding = "0" cellspacing = "0" width = "100%"><tr><td width = "50%"><img src = "2061.png" style = "vertical-align:middle;" /> </td><td width = "50%"> <sub>0</sub></td></tr></table>';

//换个思路吧,不要提取而是删减
//包括table/tr标签就再加2条
$replace = array('/<\s*td.*>/U', '/<\s*\/td\s*>/U');

echo preg_replace($replace, '', $s1);
echo '<br />';
echo preg_replace($replace, '', $s2);