Implementation content: truncate a section containing HTML Code But there is no issue that the containment mark is not closed.
PHP version address
The core part is as follows:Copy codeThe Code is as follows: function generate_brief (text, length ){
If (text. Length <length) return text;
VaR foremost = text. substr (0, length );
VaR Re =/<(\/?)
(Body | script | p | Div | H1 | H2 | H3 | H4 | H5 | H6 | Address | pre | table | tr | TD | th | input | select | textarea | object
| A | ul | ol | Li | base | meta | link | HR | BR | Param | IMG | area | input | span) [^>] * (> ?) /Ig;
VaR singlable =/base | meta | link | HR | BR | Param | IMG | area | input/I
VaR stack = new array (), posstack = new array ();
While (true ){
VaR newone = re.exe C (foremost );
If (newone = NULL) break;
If (newone [1] = ""){
VaR ELEM = newone [2];
If (ELEM. Match (singlable) & newone [3]! = ""){
Continue;
}
Stack. Push (newone [2]. touppercase ());
Posstack. Push (newone. Index );
If (newone [3] = "") break;
} Else {
VaR stacktop = stack [stack. Length-1];
VaR end = newone [2]. touppercase ();
If (stacktop = END ){
Stack. Pop ();
Posstack. Pop ();
If (newone [3] = ""){
Foremost = foremost + "> ";
}
}
};
}
VaR cutpos = posstack. Shift ();
Foremost = foremost. substring (0, cutpos );
Return foremost;
}