0

Is it possible take a value from a STRING like:

$string = ' * some parameter: A+ * Nextparameter: 0,671 kWh/24h * 
        Some another parameter value: 245 kWh/year * Last parm: 59 kg'; 

Now i know what parameters i need and a have a list:

My parameters what I'm finding (always will be the same):

$parm1 = "* some parameter:";
$parm2 = "* Nextparameter:";
$parm3 = "* Some another parameter value:";
$parm4 = "* Last parm:";

How can I get this result:

$parm1result = "A+";
.. etc ...

Or, the best way:

$result = array(
    "some parameter" => "A+",
    "Nextparameter" => "0.671", 
    ... etc ...
);

Thank you ...

2
  • COuld be great if you have a separator like "&", any other way you need to use regular expresion for match any value that you need Commented Oct 17, 2013 at 10:40
  • If you're not after a truly generic solution I think the easiest way would be to explode on "*" and explode each part of that operation on ":" ... Commented Oct 17, 2013 at 10:45

2 Answers 2

1

Sorry, last post got screwed up.

You need to split twice and apply some trimming:

<?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);
?>
Sign up to request clarification or add additional context in comments.

Comments

1

As an additional way of retrieving the parameters into an array, you can use the preg_match_all() function.

However, this might be the more complex (although shorter) way to do it:

$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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.