Doc WordPress WordPress Tricks, Tips & Snippets

27Jul/170

Strip shortcodes but keep the content within

Sometimes you might need to strip enclosing shortcodes from some content for an excerpt or teaser output. of course WordPress has a useful function for this called strip_shortcodes(), but this function also strips the content in-between the enclosing shortcodes.

If you want to strip the enclosing shortcodes itself but keep the content in-between you can use a regex like this:


<?php

$content = '[someshortcode]example text[/someshortcode]';
$result = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $content);

echo $content; // example text

?>

This would strip the shortcodes but leave the enclosed text unchanged.