分隔符决定php中的变量和值



我正在使用php。我有一个文本文件,它分隔了两个东西,如下所示:

橙色;100公斤苹果400公斤桃543千克

我想将橙色作为变量,并指定100kg作为值。

$orange="100kg";
$Apple="400kg";
$Peach="543kg";

请注意,我不想将文本文件转换为json。

您可以使用一些正则表达式来匹配您要查找的变量和值,并使用它们来生成PHP变量,如:

$fileData = '$orange="100kg";$Apple="400kg";$Peach="543kg";';
$patternVars = '/(?<=$).*?(?==)/m';
$patternValues = '/(?<="(?!;)).*?(?=")/m';
$vars = preg_match_all($patternVars, $fileData, $varMatches); // Match all variables 
$values = preg_match_all($patternValues, $fileData, $valueMatches); // Match all values 
forEach($varMatches[0] as $key => $value){
// Use the value to name your variable (hence the weird looking "$$") and set the value of this variable to the matches of your values.  
$$value = $valueMatches[0][$key];
}
var_dump($orange); // Will output "100kg"

或者看这个交互式示例。

如果我是你,我也会考虑其他选择(如果可能的话(。如果你的文件没有像你的例子一样到处格式化,你可能会得到意想不到的结果。

我不确定你想做什么。此外,给一个我们不知道名称的变量赋值不是一个好主意。然而,我想出了下面的代码:

<?php
$text = "Orange;100kg Apple;400kg Peach;543 Kg";
$regex = '/(?<variable>w+);(?<number>d+)(s+)?(k|K)(g|G)/m';
preg_match_all($regex, $text, $matches);
$length = count($matches["variable"]);
for ($i=0; $i < $length; $i++) { 
$variableName = $matches["variable"][$i];
$number = $matches["number"][$i];
${$variableName} = $number . "kg";
}
echo $Orange . PHP_EOL;
echo $Apple . PHP_EOL;
echo $Peach . PHP_EOL;
?>

输出

100kg
400kg
543kg

解释

${"variableName"}将等号之后的值分配给名称为variableName的变量。因此,如果您调用echo $variableName,它将显示分配给该变量的值。

最新更新