The [JavaScript version] of the Code that automatically generates the article summary is too troublesome for many programs to bypass this issue, and it is often done manually to decide where to truncate the code.
Implementation content: truncate a piece of text containing HTML code, but there will be no issue that the congestion mark is not closed.
Here is a PHP version! : Automatically generate the article abstract [PHP version].
The core part is as follows:
The 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;
}