Search code examples
phpreplacepreg-replaceshortcode

Replace spaces with <br /> if inside or outside of a shortcode placeholder without adding to start or end of the string


I have something like this:

[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text

How do I preg_replace (or str_replace) so <br /> gets inserted between each '][' or '] ['

EDIT:

In order to make things as clear as possible...

input:

[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text

output:

[shortcode]<br />text<br />[/shortcode]<br />[shortcode_2]<br />text<br />[/shortcode_2]<br />[button]<br />[shortcode_3]<br />text<br />[/shortcode_3]<br />[image]<br />text

Solution

  • Using preg_replace_callback

    $r = preg_replace_callback('/\]([^\]]+)?(\[)|([^\]]+$)/', function($matches) {
    
        var_dump($matches);
    
        if (!strlen($matches[1])) {
            return "";
        } else if (!isset($matches[1]) || !strlen(trim($matches[1]))) {
            return "]<br />[";
        } else {
            return "]<br />" . trim($matches[1]) . "<br />[";
        }
    
    }, '[shortcode] text [/shortcode] [shortcode_2] text [/shortcode_2][button] [shortcode_3] text [/shortcode_3] [image] text');