0

I have a string:

[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"]

The ids will vary, but how can I (in PHP) get the values?

RegExps are not my strong point but I guess we could check for everything within the quotes that comes directly after the word ids?

1
  • How about strpos + substr instead? Commented Mar 4, 2013 at 23:50

3 Answers 3

5

Regex: preg_match_all(/\d+/,$string,$matches);

Explained demo here: http://regex101.com/r/fE4fE6

Sign up to request clarification or add additional context in comments.

Comments

2

I think a simpler solution, rather than using preg_match, is to simply explode the string using " as the delimiter, where the ids will be the second element (index 1).

$string = '[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"]';

$array = explode('"', $string);

$ids = explode(',', $array[1]);

This can be quite elegant from PHP 5.4 where function array dereferencing has been added:

$string = '[gallery ids="2282,2301,2302,2304,2283,2303,2285,459,1263,469,471,1262,1261,472,608,467,607,606,466,460"]';

$ids = explode(',', explode('"', $string)[1]);

The benefit this has over preg_match is that it doesn't matter what the values are -- they could be numbers or letters or other symbols.

2 Comments

good answer, but preg_match can match anything. It just might be overkill for this simple task.
True, but you'd need to know what the pattern is for the values. With explode you don't, so it's more extensible.
0

If you wanted a non-regex solution, you could do something like this:

$str = ...;

$start = strpos($str, '"') + 1; // find opening quotation mark
$end = strpos($str, '"', $start); // find closing   ''     ''

$ids = explode(",", substr($str, $start, $end - $start));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.