Php 从字符串到数组获取值
是否可以从以下字符串中获取值:Php 从字符串到数组获取值,php,text,Php,Text,是否可以从以下字符串中获取值: $string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h * Some another parameter value: 245 kWh/year * Last parm: 59 kg'; 现在我知道我需要什么参数,并且有一个列表: 我发现的参数(始终相同): 我如何获得此结果: $parm1result = "A+"; .. etc ... 或者,最好的方法是: $re
$string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h *
Some another parameter value: 245 kWh/year * Last parm: 59 kg';
现在我知道我需要什么参数,并且有一个列表:
我发现的参数(始终相同):
我如何获得此结果:
$parm1result = "A+";
.. etc ...
或者,最好的方法是:
$result = array(
"some parameter" => "A+",
"Nextparameter" => "0.671",
... etc ...
);
谢谢…对不起,上次的帖子搞砸了 您需要拆分两次并应用一些修剪:
<?php
$string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h *
Some another parameter value: 245 kWh/year * Last parm: 59 kg';
// remove beginning and ending stars and whitespace so we don't have empty values
$string = trim($string, ' *');
// get parameters
$arr = explode('*', $string);
// trim a little more
$arr = array_map(trim, $arr);
// add stuff to array
$result = array();
foreach ($arr as $param) {
// nicer way of representing an array of 2 values
list($key, $value) = explode(':', $param);
$result[trim($key)] = trim($value);
}
var_export($result);
?>
作为将参数检索到数组中的另一种方法,您可以使用preg\u match\u all()
函数
但是,这可能是更复杂(尽管更短)的方法:
$params = array();
$string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h * Some another parameter value: 245 kWh/year * Last parm: 59 kg';
if (preg_match_all('/\*\s*([^\:]+):([^\*]+)/', $string, $m) > 0) {
foreach ($m[1] as $index => $matches) {
$params[trim($matches)] = trim($m[2][$index]);
}
}
// $params now contains the parameters and values.
如果你有一个像“&”这样的分隔符,那就太好了。如果你不是在寻找一个真正通用的解决方案,那么你需要使用正则表达式来匹配你需要的任何值。我认为最简单的方法是在上分解“*”
和在上分解操作的每个部分:“
。。。
$params = array();
$string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h * Some another parameter value: 245 kWh/year * Last parm: 59 kg';
if (preg_match_all('/\*\s*([^\:]+):([^\*]+)/', $string, $m) > 0) {
foreach ($m[1] as $index => $matches) {
$params[trim($matches)] = trim($m[2][$index]);
}
}
// $params now contains the parameters and values.