在我正在構建的應用程序中,我想使用變量中的內容創建一個數組。這是我的代碼:來自變量的PHP數組內容
$cont = '"q","w","e","r","t",';
$num = array(eval($cont));
foreach ($num as $v) {
echo "" . $v . "<br>OK<br><br>";
}
它什麼都沒有返回。我用eval試過了,沒有我做錯了什麼?
在我正在構建的應用程序中,我想使用變量中的內容創建一個數組。這是我的代碼:來自變量的PHP數組內容
$cont = '"q","w","e","r","t",';
$num = array(eval($cont));
foreach ($num as $v) {
echo "" . $v . "<br>OK<br><br>";
}
它什麼都沒有返回。我用eval試過了,沒有我做錯了什麼?
猜你在找什麼後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
..
如果字符串中最後有逗號,則最後只會打印出「OK」。爲此,您可以使用array_filter()函數來過濾空值。 – Kashyap
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>";
}
該代碼沒有任何意義 –
http://php.net/explode PS:而不是開發自定義的序列化算法,它是有道理的檢查JSON的代替。 – zerkms
你不能「評估」一個隨機的半成形表達式。它必須是有效的PHP。 –