I was wondering if someone could point me in the right direction for cleaning up this code.
WordPress uses shortcodes in the form [shortcode] to add extended functionality to posts and pages.
What I am trying to do is to return a string with all of the 'stray' brackets, ones not being used by any of shortcodes, as html entities.
What I have to work with are these variables via WordPress:
$shortcode_tags
: an array of all shortcodes as strings (without brackets)get_shortcode_regex()
: combines all registered shortcode tags into a single regular expression. (I am not using this in the code below)
function find_stray_brackets ($content) {
// this code repalces all occurences of every shortcode with special brackets.
// It then replaces remaining 'stray' brackets with the HTML character entitiy.
global shortcode_tags;
foreach($shortcode_tags as $k=>$item)
{
$pattern='/\[('.$k.'.*?(?=\]))\]/';
$content=preg_replace($pattern,'*{*$1*}*',$content);
$pattern='/\[\/('.$k.'.*?(?=\]))\]/';
$content=preg_replace($pattern,'*{*/$1*}*',$content);
}
$content=str_replace('[','[',$content);
$content=str_replace(']',']',$content);
$content=str_replace('*{*','[',$content);
$content=str_replace('*}*',']',$content);
return($content);
}
The approach is to replace all of the brackets that surround shortcodes with special characters-> replace stray brackets with html entities -> re-insert original brackets
My end goal is to put all of the text between short codes (including before the first and after the last shortcode) into an array. I couldn't get the regex that Wordpress produces to do what I wanted, so wrote my own regex that relies on brackets - this is why I need to deal with the strays.
Here is the regex that WordPress outputs and some sample text with nested shortcodes.