Executing WordPress Shortcodes in a String

Viewed 8603

I have a string that may contain shortcodes such as "this is a string with [anyshortcode1] and this is [anyshortcode2]". I want to display the string with the shortcodes running where they are placed. When I echo this string out, it doesn't do the shortcodes, it just prints them out leaving them in brackets. I tried to fix this by using code like the following:

$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]";
$pattern = get_shortcode_regex();
preg_match_all("/$pattern/",$string_with_shortcodes, $matches);
foreach ($matches[0] as $short) {
    $string_with_shortcodes = str_replace($short, 'do_shortcode("' . $short . '")', $string_with_shortcodes);
}
eval("\$string_with_shortcodes = \"$string_with_shortcodes\";");
echo $string_with_shortcodes;

This successfully does the string replacement, but causes an error with the eval function:

Parse error: syntax error, unexpected T_STRING

Am I using the eval function wrong? Or is there a simpler way to accomplish running shortcodes from a string?

2 Answers
Related