由于您不知道未闭合的开始标签是什么,因此您正在创建一个简单的解析器。
每次遇到开放的尖括号时,您都需要遍历您的内容并停止<
。这真的应该用AWK来完成;但是如果你必须使用 PHP,你会做这样的事情
<?php
$file = file_get_contents('path/to/file');
$file = preg_replace( '/[\n\r\t]/' , '' , $file );
$pieces = explode( '<' , $file );
if ( !$pieces[0] ) array_shift($pieces);
/* Given your example code, $pieces looks like this
$pieces = array(
[0] => 'td>',
[1] => 'ins>sample content',
[2] => '/td>',
[3] => 'td>other content',
[4] => '/td>',
[5] => '/tr>',
[6] => 'tr>',
[7] => 'td>remaining',
[8] => '/ins>other copy',
[9] => '/td>'
);
*/
$openers = array();//$openers = [];
$closers = array();//$closers = [];
$brokens = array();//$brokens = [];
for ( $i = 0 , $count = count($pieces) ; $i < $count ; $i++ ) {
//grab everything essentially between the brackets
$tag = strstr( $pieces[$i] , '>' , TRUE );
$oORc = strpos( $pieces[$i] , '/' );
if ( $oORc !== FALSE ) {
//store this for later (and maintain $pieces' index)
$closers[$i] = $tag;
$elm = str_replace( '/' , '' , $tag );
if ( ( $oIndex = array_search( $elm , $openers ) ) && count($openers) != count($closers) ) {
//more openers than closers ==> broken pair
$brokens[$oIndex] = $pieces[$oIndex];
$cIndex = array_search( $tag, $closers );
$brokens[$cIndex] = $pieces[$cIndex];
//remove the unpaired elements from the 2 arrays so count works
unset( $openers[$oIndex] , $closers[$cIndex] );
}
} else {
$openers[$i] = $tag;
}//fi
}//for
print_r($brokens);
?>
索引 in$brokens
是$pieces
出现格式错误的 html 的索引,它的值是有问题的标签及其内容:
$brokens = Array(
[1] => ins>sample content
[8] => /ins>other copy
);
警告这不考虑像<br />
或这样的自动关闭标签<img />
(但这就是为什么你应该使用已经存在的许多软件应用程序之一)。