Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wrote this function which should do just what you want. It counts n numbers of characters (except those in tags) and then closes tags which needs to be closed. Example use included in code. The code is in python, but should be really easy to port to other languages, such as php.</p> <pre><code>def limit(input, length): """Splits a text after (length) characters, preserving bbcode""" stack = [] counter = 0 output = "" tag = "" insideTag = 0 # 0 = Outside tag, 1 = Opening tag, 2 = Closing tag, 3 = Opening tag, parameters section for i in input: if counter &gt;= length: # If we have reached the max length (add " and i == ' '") to not make it split in a word break elif i == '[': # If we have reached a tag insideTag = 1 elif i == '/': # If we reach a slash... if insideTag == 1: # And we are in an opening tag insideTag = 2 elif i == '=': # If we have reached the parameters if insideTag &gt;= 1: # If we actually are in a tag insideTag = 3 elif i == ']': # If we have reached the closing of a tag if insideTag == 2: # If we are in a closing tag stack.pop() # Pop the last tag, we closed it elif insideTag &gt;= 1:# If we are in a tag, parameters or not stack.append(tag) # Add current tag to the tag-stack if insideTag &gt;= 0: # If are in some type of tag insideTag = 0 tag = "" elif insideTag == 0: # If we are not in a tag counter += 1 elif insideTag &lt;= 2: # If we are in a tag and not among the parameters tag += i output += i while len(stack) &gt; 0: output += '[/'+stack.pop()+']' # Add the remaining tags return output cutText = limit('[font]This should be easy:[img]yippee.png[/img][i][u][url="http://www.stackoverflow.com"]Check out this site[/url][/u]Should be cut here somewhere [/i][/font]', 60) print cutText </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload