Html
<table>
<tr><td></td></tr> //1st row
<tr><td></td></tr> //2nd row
<tr><td></td></tr> //3rd row
<tr><td></td></tr> //4th row
<tr><td></td></tr> //5th row
</table>
我想做什么
if (intval($rows) > 3) {
delete all rows after 3rd row
}
我正在使用下面的php代码来获取html页面
$index = substr_count(strtolower(file_get_contents('index.html')), '<tr>');
我希望我的问题足够清楚,能够理解
完整代码
<?php
$htaccess = file_get_contents('index.html');
$new_htaccess = str_replace('<table><tr><td>first row data</td></tr>', '<table><tr><td>first row data</td></tr><tr><td>sec row data</td></tr>', $htaccess);
$pos = strpos($htaccess, $ssa);
if ($pos == false) {
file_put_contents('index.html', $new_htaccess);
} else {
}
$index = substr_count(strtolower(file_get_contents('index.html')), '<tr>');
if (intval($index) > 20) {
//delete end rows and add a new one
}
?>
这里有一个非常简单且未经测试的方法:
//--- create a new DOM document
$doc = new DOMDocument();
//--- load your file
$doc->loadHTMLFile("filename.html");
//--- point to the tables [0] means first table in the file
$tables = $doc->getElementsByTagName('table')[0];
//--- get all the tr within the specified table
$tr = $tables->getElementsByTagName('tr');
//--- loop backwards
for( $x=count($tr)-1; $x>2 $x-- ) {
//--- remove the node (not sure which one will work)
$old = $tr->removeChild($tr[$x]);
$old = $tr->removeChild( $tr->item($x) );
}
//--- save the new file
$doc->saveHTMLFile("/tmp/test.html");
参考文献:http://www.php.net/manual/en/domdocument.loadhtmlfile.phphttp://www.php.net/manual/en/domdocument.getelementsbytagname.phphttp://www.php.net/manual/en/domnode.removechild.phphttp://www.php.net/manual/en/domdocument.savehtmlfile.php
希望这能有所帮助。
我将首先使用正则表达式(如'<table>.+<'/table>'
)提取表,然后剥去CCD_ 2标签。
使用以<tr>
为分隔符的exlode
将字符串转换为数组并最终使用阵列的前3个项目来重建表
这就是我尝试的方式,不确定它是否适用于你的情况。很明显,您正在抓取另一个站点,因此这在很大程度上取决于代码的一致性。
jeff
发布了一个很好的解决方案,因此如果您有兴趣使用任何第三方库
我建议你使用ganon.php
<?php
require_once( "ganon.php" );
// Your html
$html = '<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>4</td></tr>
<tr><td>5</td></tr>
</table>';
// load the html
$html = str_get_dom( $html );
// search for our table
if ( $table = $html( "table", 0 ) ) {
// get all rows which is after 3rd row, here 0 is 1, so 3rd row is 2
if ( $rows = $html( "tr:gt(2)" ) ) {
// loop through rows
foreach( $rows as $row ) {
// .... and delete them
$row->delete();
}
}
}
// output your modified html
echo $html;
?>
使用jquery,您可以尝试以下
<script src='http://code.jquery.com/jquery-latest.min.js' type="text/javascript" ></script>
<?php
$html = '<table id="mytable">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
<tr><td>4</td></tr>
<tr><td>5</td></tr>
</table>';
echo $html;
?>
<script>
$(function() {
var TRs = $("#mytable tr");
for(i=0; i<TRs.length; i++) {
if(i>=3) {
$(TRs[i]).remove();
}
}
});
</script>