jaseUK
jaseUK

Reputation: 313

PHP - Variable processed and return a value

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!

Upvotes: 0

Views: 86

Answers (2)

Hrach
Hrach

Reputation: 347

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';

Upvotes: 0

Ceeee
Ceeee

Reputation: 1442

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

Upvotes: 1

Related Questions