提取、分割table中的td数据
在自己的学习玩弄中,遇到了这么一个需求,需要提取table中的数据,显而易见的,有用的数据即是table中td的数据。当然我试过百度,但是没找到符合我心意的,于是自己书写了一个DataSplit工具类,专门处理数据的分割,而table分割作为其中一个成员方法,同时用到了该类中的其他方法,在此贴出代码。
class DataSplit {
/*
*去除空格
*/
public static function trim($content){
return preg_replace("/[\s]{1,}/", "", $content);
}
/*
* 字符串截取
*/
public static function substring($src, $fromString, $toString) {
$fromPos = 0;
if ($fromString != null && strlen($fromString) > 0) {
$fromPos = strpos($src, $fromString);
$fromPos += strlen($fromString);
}
$toPos = strpos($src, $toString, $fromPos);
return substr($src, $fromPos, $toPos - $fromPos);
}
/*
* 分割table,tr,td
*/
public static function splitTable($content) {
$table = self::substring($content, '<table', '</table>');
$table[0] = '<table' . $table[0];
$trs = explode('<tr>', $table);
$array = array();
foreach ($trs as $val){
$tds = explode('<td>', $val);
$arr = array();
foreach ($tds as $tdVal){
array_push($arr, self::trim(strip_tags($tdVal)));
}
array_push($array, $arr);
}
return $array;
}
}
转载需经作者允许并注明出处(http://nit.hiunique.com/php/5.html)
来自:你好创造者