We help IT Professionals succeed at work.
Get Started

echo variables to screen

rgb192 asked
Last Modified: 2012-05-11
want to store values in variables and echo to screen
so I can save these variables
see related question

echo $timestamp $costvariable $cost $productid
$string="05/26/2011 03:26:58PM | dbquery | | SQL: UPDATE products SET cost2 = '372' WHERE productid = '151951' | Error: test\n05/26/2011 05:44:48PM | dbquery | | SQL: UPDATE products SET cost3 = '445.00' WHERE productid = '151529' | Error: test";

* @param String $string is the source string
* @param Array  $fieldNames is the basename for all
*               fields that needs to be matched. When 
*               provided with array('cost', 'productid') the
*               function will match 'cost', 'cost1', 'cost2',
*               etc, 'productid', 'productid1', etc.
function findFields($string, $fieldNames) {
    // Local variable to capture return value
    $result = array();
    // Part of the regular expression that will match field names.
    $q = implode('|', array_map('preg_quote', $fieldNames));
    // Regular expression that will find the variables and values
    $regexp = '/(('.$q.')\d*)\s*=\s*([\'"])([^\\3]*?)\\3\s*/';
    // Run through all lines
    foreach (explode("\n", $string) as $lineNumber => $line) {
        // Make the line human readable. Escape this line
        // for easier processing in later stages
        $lineNumber = 'Line#'. ($lineNumber + 1);
        // Explode into cells to get the timestamp / sql columns
        $array = explode('|', $line);
        // Store timestamp
        $result[$lineNumber] = array('timestamp' => $array[0]);
        // Process all variable findings
        if (preg_match_all($regexp, $array[3], $m)) {
            foreach($m[1] as $index => $field) {
                $value = $m[4][$index];
                $result[$lineNumber][$field] = $value;
    return $result;

$results = findFields($string, array('cost','productid'));

echo '<pre>';

Open in new window

Watch Question
Most Valuable Expert 2011
Author of the Year 2014
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE