I saw a PHP interview question and did it. I don't know if there is any better solution. The questions are as follows: aaa & lt; em & gt; sss & lt; em & gt; ddd string, write a function CutStr ($ str, $ max) to achieve truncation: 1) if $ max is longer than $ str, $ str2 is returned. & lt; em & gt; and & lt; em & gt; are not included in the length calculation range. For example, if CutStr (aaa & saw a PHP interview question, do not know if there is any better way
The questions are as follows,
Aaa
SssDdd string, write a function CutStr ($ str, $ max) to achieve interception:
1) if $ max is longer than $ str, $ str is returned.
2)
AndIt is not included in the length calculation range.
Example:
If CutStr ("aaa
SssDdd ", 6) returns aaa
Sss.
If CutStr ("aaa
SssDdd ", 4) returns aaas, not including
Tag
My first response is regular, and then...
Var str = "aaaSssDdd "; function cutStr (str, max) {// firstAndRemove them first, and then record their location var reg = new RegExp ("(.*?)(.*?)(.*?) "); Var emSub = str. indexOf (""); Var em2Sub = str. indexOf (""); Var newstr = str. replace (reg, "$1 $2 $3"); // returns the original if (! /^ \ D + $ /. test (max) | max> = newstr. length) return str; newstr = newstr. substring (0, max); if (max <= emSub) {// less than three return newstr;} else if (max <= em2Sub-4 & max> emSub) {// greater than three, less than six (note:-4 is used to subtract the firstLocation occupied) var tempReg = new RegExp ("(\ w {" + emSub + "}) (\ w *?) "); Return newstr. replace (tempReg," $1$2 ");} else {// greater than six var tempReg = new RegExp (" (\ w {"+ emSub + "}) (\ w {"+ (em2Sub-emSub-4) + "}?) (\ W *?) "); Return newstr. replace (tempReg," $1$2$3 ") ;}} alert (cutStr (str, 7 ));?
I think this method is stupid. Is there any other good method?
I thought of it. it was so simple that I thought it was complicated...
Var str = "aaaSssDdd "; function cutStr (str, max) {var emSub = str. indexOf (""); Var em2Sub = str. indexOf (""); // If it is not a number or negative number, or greater than the character length, the original character if (! /^ \ D + $ /. test (max) | max> = str. length-9) return str; else if (max> em2Sub-4) return str. substring (0, max + 9); else if (max> emSub) return str. substring (0, max + 4); else return str. substring (0, max);} alert (cutStr (str, 7 ));?