在我正在构建的应用程序中,我想使用变量中的内容创建一个数组。这是我的代码:
$cont = '"q","w","e","r","t",';
$num = array(eval($cont));
foreach ($num as $v) {
echo "" . $v . "<br>OK<br><br>";
}
它什么都不返回。我用eval试了一下,没有我做错了什么?
答案 0 :(得分:1)
猜猜你正在照顾的是explode()
:
$cont = '"q","w","e","r","t","y"';
$num = explode(',',$cont);
foreach ($num as $v) {
echo "" . $v . "<br>OK<br><br>";
}
输出
"q"
OK
"w"
OK
..
答案 1 :(得分:0)
eval
是邪恶的, most of time 。您可以改为使用preg_match_all
:
$cont = '"q","w","e","r","t",';
preg_match_all("/\"([^\"]+)\"/", $cont, $matches);
$num = $matches[1];
foreach ($num as $v) {
echo "$v<br>OK<br><br>";
}
或者只是创建数组:
$num = array("q","w","e","r","t");
foreach ($num as $v) {
echo "$v<br>OK<br><br>";
}
但如果所有这些警告和替代方案对您来说还不够,并且您坚持使用eval
,请尝试以下操作:
$cont = '"q","w","e","r","t",';
eval("\$num = array($cont);");
foreach ($num as $v) {
echo "$v<br>OK<br><br>";
}