'Remove shortcode from excerpt (have codes)

I have this line of code displaying the excerpt in the theme:

<p class="desc"><?php echo mb_strimwidth(strip_tags(get_the_content('')), 0, 220, '...'); ?></p>

How do I put this code in to strip out the shortcodes from the excerpt?

$text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text);

I'm just getting into cutting up PHP so I'm needing just a little bit of help with this one.

Thanks!



Solution 1:[1]

Instead of re-inventing the wheel, I recommend you using the core WordPress function strip_shortcodes().

<p class="desc"><?php echo mb_strimwidth(strip_shortcodes(strip_tags(get_the_content(''))), 0, 220, '...'); ?></p>

Solution 2:[2]

DONT USE REGEX in this case!

REGEX will remove your own notes from excerpts, for example:
Hello, on May 27 [1995] , blabla

so, better to use built-in function strip_shortcodes, which detects registered shortcodes and removes them:

add_filter('the_excerpt','myRemoveFunc'); function myRemoveFunc(){
    return mb_strimwidth(strip_shortcodes(get_the_content()), 0, 220, '...');
}

Solution 3:[3]

Posting a solution worked for me based on @T.Todua solution:

add_filter('get_the_excerpt','clean_excerpt');
function clean_excerpt(){
    $excerpt = get_the_content();
    $excerpt = strip_tags($excerpt, '<a>'); //You can keep or remove all html tags
    $excerpt = preg_replace("~(?:\[/?)[^/\]]+/?\]~s", '', $excerpt);

    return ($excerpt) ? mb_strimwidth($excerpt, 0, 420, '').new_excerpt_more() : '';
}

function new_excerpt_more($more = '') {
    global $post;
    return '...  <a href="'.get_permalink($post->ID).'" class="readmore">Read More ยป</a>';
}

I split it into two functions since I also use the "more" filter as follow:

add_filter('excerpt_more', 'new_excerpt_more');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 T.Todua
Solution 3 xxx