Get array of shortcodes within string

I do have an post/page where the shortcode "question" occurs many times. What is the best way to get an array of all the "question" shortcodes with their related parms?

[question a=1 b=2 c=3 ]
[question b=2 c=3 ]
[question a=1 b=2 ]
[question]

Topic regex shortcode Wordpress

Category Web


You can also use the regular expression provided by WordPress itself using get_shortcode_regex:

function wpse250308_get_questions() {
    global $post;
    if ( preg_match_all(get_shortcode_regex('question'), $post->post_content, $questions ) ) {
        $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
        // $questions will contain the array of the question shortcodes
        // but also, get_shortcode_regex returns a regex that provides some useful capture groups:
        // the get_shortcode_regex from WP provides the matches:
        // 1 – An extra [ to allow for escaping shortcodes with double [[]] 
        // 2 – The shortcode name 
        // 3 – The shortcode argument list 
        // 4 – The self closing / 
        // 5 – The content of a shortcode when it wraps some content. 
        // 6 – An extra ] to allow for escaping shortcodes with double [[]]
        //Do your stuff
    }
}  

function wpse250308_get_questions() {
    global $post;
    if ( preg_match_all('/\[question(.*?)\]/', $post->post_content, $questions ) ) {
        $questions = array_key_exists( 1 , $questions) ? $questions[1] : array();
        // $questions will contain the array of the question shortcodes
        //Do your stuff
    }
}  

$post isn't available before wp. So, you have to hook on it or actions that fires later.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.