0

I have the following string stored in my database: [gallery ids="442,443,444"].

I'd like to take the values from ids i.e. 442, 443, 444 and run a foreach loop.

So it would basically loop through all the integers inside ids.

How can I do this with PHP?

3 Answers 3

1

You need to first extract the ids collectively, then make them into an array.

You could for example split the string using double quotes:

list (,$rawIds) = preg_split('#"#', $string);

and then explode the ids:

$ids = preg_split('#,\\s*#', $rawIds);

The \s* takes care of possible whitespaces (e.g. "21,22,23, 24,25").

At that point you use $ids as an array:

foreach ($ids as $index => $id) {
    print "ID #{$index} is {$id}\n";
}

ID #0 is 5
ID #1 is 8
ID #2 is 12

However, you'd better verify how the string got created: e.g. if it is by any chance JSON, you'd be better served by using json_decode($string, true).

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

1 Comment

This is perfect. Can you explain how I then use a foreach loop on each of the IDs?
1

You can try this small script:

<?php
// get the value from the Database
$ids = $record;  // get some procedure to get the value from the database.
// explode the value to get the list ids
$list = explode("=",$ids);
// get the list ids only
$elements = str_replace("\"","",$list[1]);
// extract all ids from the list
$array_list = explode(",",$elements);
// trigger loop to get each value
foreach($array_list  as $ value){
 echo $value."<br />"; // value for each element, i.e. 442, 443, 444,....
}
?>

Comments

1

Try this way

$txt = '[gallery ids="442,443"]';
preg_match_all('!\d+!', $txt, $match);
print_r($match); // get all matches data in an array

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.