php - Regex/preg_replace to remove extra line breaks between [font#ABCDEF]$text[/font] BBcode -


there blog users can post messages. can use font bb code. problem - current script doesn't remove multiple line breaks when text posted between font bb code (it works correctly clear text).

so idea add preg_replace function removes lines text posted within font bb code. font bb code starts with: [font#abcdef] , ends [/font].

for example:

[font#ff0000]    text in red.  hello world. how you?       good, thanks.   [/font] 

after preg_replace there should maximum of 2 line breaks left (eg. if adds 6 line breaks, should reduced 2; if adds 1 or 2 line breaks should left entered, ie. 1 or 2 respectively), etc.

here current attempt, doesn't appear work though should close correct solution, hope:

$text=preg_replace("#(\[font[^\]]*?\])[\r\n ]+#i", "\\1", $text); $text=preg_replace("#[\r\n ]+(\[/font\])#i", "\\1", $text); $text=preg_replace("#(\[/font\])[\r\n]{2,}#i","\\1\n", $text); 

(ideally best not leave line breaks right after opening [font#abcdef] tag , right before closing [/font] tag because line breaks aren't needed there @ all.

you can use kind of pattern uses \g anchor. anchor matches position after last match, useful obtain contiguous results:

$pattern = '~ (?:     \g(?!\a)      # position after last match   |              # or     \[font[^]]*]  # start tag      (?: \k \r+ (*accept) )? # if leading newlines,                              # (*accept) forces pattern succeed immediatly ) (?> [^\r\n[]* \k \r )*? # lines until: # (\k removes on left match result) (?:     \r+(?=\[/font]) # end    |                # or     \r \k \r+       # more 2 newlines ) ~xi';  $txt = preg_replace($pattern, '', $txt); 

there other way preg_replace_callback: pattern find content between font tags , callback function removes uneeded newlines:

$txt = preg_replace_callback('~\[font[^]]*]\k[^[]+(?=\[/font])~i', function ($m) {     return preg_replace('~\r\r\k\r+~', '', trim($m[0], "\r\n")); }, $txt); 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -