0

I need to process a variable through some validation to return a value of which I can use later on in my script. My $var is coming from a GET.

Example: A variable may come through like below.

$var = 'main server app1 stop'

I need to break up the string as follows.

main server needs to look up a list like below and return the ip address.

192.168.10.1 = 'main server' 
192.168.10.2 = 'backup server'

app1 also needs to be looked up in a list and return the match.

service httpd = 'app1' 
service iptables = 'app2'

Then bring back the relevant matches together. In this example I would want the following returned.

192.168.10.1 service httpd stop

I hope I have explained this clear enough. If not tell me what I need to detail more.

Thanks!

1
  • Consider reading about explode (php.net/manual/en/function.explode.php) to convert a string to an array - it's simpler to irritate an array than a string in my opinion. Commented Mar 22, 2016 at 8:54

2 Answers 2

1

PLEASE, PLEASE read more about explode() and arrays in PHP but here's the cheese:

$var = 'main server app1 stop';

$server = array(
    'main server'   => '192.168.10.1',
    'backup server' => '192.168.10.2',
);

$service = array(
    'app1' => 'service httpd',
    'app2' => 'service iptables',
);

$arr = explode(' ', $var);

echo $server["$arr[0] $arr[1]"] . ' ' . $service[$arr[2]] . ' ' . $arr[3];

output:

192.168.10.1 service httpd stop
Sign up to request clarification or add additional context in comments.

Comments

0

I would suggest doing the following

$server = (strpos($var,'main') !== false) ? '192.168.10.1' 
                                          : '192.168.10.2' ;

$service = (strpos($var,'app1') !== false) ? 'httpd' : 'iptables';
$output = $server . ' service ' . $service . ' stop';

2 Comments

Would this only work with 2 values in the list? As I have now added multiple items in the lists.
if you'll have more values then @Ceeee's solution is more preferable

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.