Style
First of all, you don't need the foreach
loop, preg_replace accepts mixed variables, e.g. arrays, see Example #2: http://www.php.net/manual/en/function.preg-replace.php
Answer
Use this regex to remove all line breaks between two tags (here table and row):
(\[table\]([^\r\n]*))(\r\n)*([^\r\n]*\[row\])
The tricky part is to replace it (See also this: preg_replace() Only Specific Part Of String):
$result = preg_replace('/(\[table\][^\r\n]*)(\r\n)*([^\r\n]*\[row\])/', '$1$4', $subject);
Instead of replacing with ''
, you replace it only the second group ((\r\n)*
) with '$1$4'
.
Example
[table] // This will also work with multiple line breaks
[row]
[col]Column1[/col]
[col]Column2[/col]
[col]Column3[/col]
[/row]
[/table]
With the regex, this will output:
[table] [row]
[col]Column1[/col]
[col]Column2[/col]
[col]Column3[/col]
[/row]
[/table]