Jul8th
一个实现html代码标记补全的php函数代码
编程技术
0
很多个人博客程序都有是摘要显示的,在对html截取分割时,往往会因为截取位置不确定,导致内容在显示是页面错乱,所以在截取html内容时,我们利用正则表达式写个补全函数,下面是php实现函数代码。
<?php
/**
* close all open xhtml tags at the end of the string
* @param string $html
* @return string
* @author Milian Wolff <mail@milianw.de>
*/
function closetags($html) {
#put all opened tags into an array
preg_match_all('#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
$openedtags = $result[1];
#put all closed tags into an array
preg_match_all('#</([a-z]+)>#iU', $html, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
# all tags are closed
if (count($closedtags) == $len_opened) {
return $html;
}
$openedtags = array_reverse($openedtags);
# close tags
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)){
$html .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $html;
}
$str="<table><tr><td>测试<img src=''/>";
echo closetags($str);
?>
其中str是一个测试字符串,包含了一个未结束的html标记代码,通过函数处理后,会自动添加关闭标记。非常实用!
文章作者:电子商务与网络营销-张遂华(乞丐根据地)
本文地址:http://www.zhangsuihua.cn/zhuanqianjishu/193.html
版权所有 © 转载时必须以链接形式注明作者和原始出处!


to "一个实现html代码标记补全的php函数代码"