PHP Regex; extract first matching ID in WordPress shortcode

Having this string

$string = '';

How could I extract the first id in ids?

Read More

So far I have succeeded to extract all the ids, then used split;

$output = preg_match_all('/(.+?)['"]]/', $string, $matches);
list($extracted) = split(',', $matches[1][0]);

There must be something simpler using only regex, right?

Thanks 🙂

Related posts

Leave a Reply

3 comments

  1. You could try the below regex to match the first id in id’s,

    [gallery.+ids="K[^,]*
    

    OR

    [gallery.+ids="Kd+
    

    DEMO

    Your PHP code would be,

    <?php
    $string = '[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]';
    $pattern = '~[gallery.+ids="K([^,]*)~';
    if (preg_match($pattern, $string, $m)) {
        $yourmatch = $m[0]; 
        echo $yourmatch;
        }
    ?> //=> 501
    
  2. How could I extract the first id in ids?

    Get the matched group from index 1.

    bids="(d+)
    

    Here is DEMO


    OR try with Positive Lookbehind

    (?<=bids=")d+
    

    Here is DEMO

    Sample code:

    $re = "/(?<=\bids=")\d+/";
    $str = "[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]";
    
    preg_match_all($re, $str, $matches);
    
  3. Whatever you are trying here looks weird. You don’t need regular expressions to get the shortcode params. Instead use the default, built-in function from WordPress.

    Example from codex.wordpress.org:

    // [bartag foo="foo-value"]
    function bartag_func( $atts ) {
        $a = shortcode_atts( array(
            'foo' => 'something',
            'bar' => 'something else',
        ), $atts );
    
        return "foo = {$a['foo']}";
    }
    add_shortcode( 'bartag', 'bartag_func' );
    

    See: WordPress Codex – The Shortcode API

    Update – get the first ID:

    // [gallery link="file" ids="501,502,503,504,505,506,507,508,509"]
    function gallery_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'link' => 'file',
            'ids' => array(),
        ), $atts );
    
        $ids = explode( ',', $atts );
    
        // strip the first ID from the array…
        $first_id = array_shift( $ids );
        // …or just select it
        $first_id = $ids[0];
    
        return $first_id;
    }
    add_shortcode( 'gallery', 'gallery_shortcode' );