Question

Please excuse me if I am asking a wrong question or impossible one, I am a newbie to PHP. I have following PHP code

    <?php
    if ($this->arrCustomFields) {
        foreach ($this->arrCustomFields as $field) {

            if($field['blnView']) {
                echo 'var '.preg_replace('/\s+/', '_', strtolower($field['lbl']->Name)).' = "'.$field['lbl']->Text.'";';
            }

        }

    }
?>

This code produces following variable that I use in a javascript on the same page.

var optic_drive = "No CD/DVD Media Installed";
var power_supply = "No PSU";
var ram = "2 GB";
var web_cam = "No";
var processor = "No Processor Installed";
var tested_by = "FM";
var psu = "None";
var data_storage = "Not Installed";
var grade = "B";
var serial_no = "24234234";
var hp_models = "D2200-VC"

Notice above var hp_models = "value" is one the variables that has dynamic variable name and I want to convert this variable to static name. The reason is that if I am viewing Dell, IBM, or other models this variable name will be changing dynamically to vendor name, for example "var ibm_models", "var dell_models", "var sony_models" and so on. I want to convert this variable name to a static name such somemodel or prodmodel regardless of the vendor.

So I should be able to use it something like following.

<?php
echo $_models;
?>

I should be able to get the value of the variable regardless of the vendor name. So with this variable I am using "_" underscore as a separator, only the first part changes dynamically for each record and the second part which is models is static.

I hope I was able to explain well.

Était-ce utile?

La solution

Managed to get the desired results by using preg_replace.

    <?php
    if ($this->arrCustomFields) {
        foreach ($this->arrCustomFields as $field) {

            if($field['blnView']) {
$field['lbl']->Name = preg_replace("/.*Models/", "mymodels", $field['lbl']->Name);
                echo 'var '.preg_replace('/\s+/', '_', strtolower($field['lbl']->Name)).' = "'.$field['lbl']->Text.'";';
            }

        }

    }
?>

Thanks to https://stackoverflow.com/users/2284641/johannes-h

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top