How would I use str_replace to find every ending square bracket ‘]’ and remove 2 or less linebreaks from the end. So, if there were 1 or 2 line breaks after ] it’d remove all. If there were 3 you’d end up with 1 after the ]. 4 you’d end up with 2 after etc.
Thanks for your help
Since you mentioned
str_replace, I assume that you are using PHP (you should add a tag for that if this is the case!). And since you tagged regular expressions you might want to usepreg_replaceinstead. This should work rather platform-independently then:where
$stris obviously your original string.Note that the
]gets escaped, because it’s a special regex character (used for character classes). The round brackets just contain a list of all possible linebreaks. The?:is optional and more relevant for complex regular expressions where you need to access captured subpatterns (in fact the?:says, don’t match this subpattern, because I don’t need it). And the{1,2}simply says, match one or two of those. And since regular expressions are greedy by default, it will take two if it can.EDIT: One more thought. You could solve this with
str_replace, but not so well in one go for all possible linebreaks (becausestr_replacedoesn’t support alternatives). This example might give you an idea.