numediaweb
numediaweb

Reputation: 17010

PHP Regex; extract first matching ID in WordPress shortcode

Having this string

$string = '[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]';

How could I extract the first id in ids?

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

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

There must be something simpler using only regex, right?

Thanks :)

Upvotes: 3

Views: 1621

Answers (3)

feeela
feeela

Reputation: 29932

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' );

Upvotes: 1

Braj
Braj

Reputation: 46841

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);

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

You could try the below regex to match the first id in id's,

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

OR

\[gallery.+ids=\"\K\d+

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

Upvotes: 1

Related Questions