我有以下字符串存储在我的数据库:[gallery ids="442,443,444"]
。爆炸阵列和运行foreach循环
我想从ids
即442
,443
,444
取值并运行一个foreach循环。
所以它基本上会遍历ids
内的所有整数。
我该怎么用PHP做到这一点?
我有以下字符串存储在我的数据库:[gallery ids="442,443,444"]
。爆炸阵列和运行foreach循环
我想从ids
即442
,443
,444
取值并运行一个foreach循环。
所以它基本上会遍历ids
内的所有整数。
我该怎么用PHP做到这一点?
您需要先提取ID,然后将它们组成一个数组。
list (,$rawIds) = preg_split('#"#', $string);
,然后爆炸的ID:
$ids = preg_split('#,\\s*#', $rawIds);
的\ S *照顾可能空格(如“21,22
例如,你可以使用双引号分割字符串,23,24,25“)。
在您使用$ids
作为数组这一点:
foreach ($ids as $index => $id) {
print "ID #{$index} is {$id}\n";
}
ID #0 is 5
ID #1 is 8
ID #2 is 12
不过,你最好验证字符串是怎么创建的:例如如果是JSON的话,最好使用json_decode($string, true)
。
你可以试试这个小脚本:
<?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,....
}
?>
尝试这种方式
$txt = '[gallery ids="442,443"]';
preg_match_all('!\d+!', $txt, $match);
print_r($match); // get all matches data in an array
这是完美的。你能解释我如何在每个ID上使用foreach循环吗? – michaelmcgurk
谢谢@lserni :) – michaelmcgurk