日期:2014-05-17  浏览次数:20410 次

来问正则表达式了!!
<TABLE   style= "WIDTH:   241pt;   BORDER-COLLAPSE:   collapse "   cellSpacing=0   cellPadding=0     rowspan=6   width=321   border=1   x:str   COLspan=4> <tr> <td> testtesttes </td> </tr> </table>

想通过preg_replace函数把table里的属性只留其中的两项rowspan=6   和colspan=4,此函数里的正则该怎么写??


------解决方案--------------------
$str = ' <TABLE style= "WIDTH: 241pt; BORDER-COLLAPSE: collapse " cellSpacing=0 cellPadding=0 rowspan=6 width=321 border=1 x:str COLspan=4> <tr> <td> testtesttes </td> </tr> </table> ';
$str = preg_replace( '/\ <table([^\> ].*)?rowspan=[\ "\ ']?([0-9]+)[\ "\ ']?(\s.*)?colspan=[\ '\ "]?([0-9]+)[\ '\ "]?([^\> ].*?)?\> /i ', ' <table rowspan=$2 colspan=$4> ',$str);
echo htmlspecialchars($str);
------解决方案--------------------
:P
$str = ' <TABLE style= "WIDTH: 241pt; BORDER-COLLAPSE: collapse " cellSpacing=0 cellPadding=0 rowspan=6 width=321 border=1 x:str COLspan=4> <tr> <td> testtesttes </td> </tr> </table> ';
$str = preg_replace( '/\ <table([^\> ].*)?(rowspan|colspan)=[\ "\ ']?([0-9]+)[\ "\ ']?(\s.*)?(colspan|rowspan)=[\ '\ "]?([0-9]+)[\ '\ "]?([^\> ].*?)?\> /i ', ' <table $2=$3 $5=$6> ',$str);
echo htmlspecialchars($str);
------解决方案--------------------
我也贴一个,本贴考虑到的可确保的情况有
1、避免出现引号错误,如:rowspan= "2 '等;
2、避免等号前后出现空格、换行等,如rowspan =
"2 "。

$str = preg_replace( '/\ <table[^\> ]+(rowspan|colspan)[\s\r\n]*=[\s\r\n]*([\ "\ ']?)(\d+)\2[^\> ]+(colspan|rowspan)[\s\r\n]*=[\s\r\n]*([\ '\ "]?)(\d+)\5[^\> ]*\> /i ', ' <table \1=\3 \4=\6> ',$str);