Sunday, 8 September 2013

Breaking string up based on content of string

Breaking string up based on content of string

To start: This is a school project. I know this system will have flaws!
What: I am trying to parse a string to determine what the user desires.
Example 1: Turn my kitchen lights on and my bedroom and living room lights
off.
Example 2: Turn my kitchen lights on and my bedroom lights on and living
room lights off.
Example 3: Turn my kitchen and my bedroom and living room lights off.
This is an overly simplified example but please note that I want to scale
beyond these three room as well as just controlling the lights example:
outside ceiling fan on...
How: I am currently using a few while loops to iterate through an array
and the checking if certain strings are in the array.
More how: My idea was to first split on the string on the "and". I then
check each array for a on or off. If it does not have a on or off i join
the array with the next.
Help: I would love to clean this concept up as well as see someone else s
ideas...I am up for anything ..
Thanks JT
CODE:
$input = 'kitchen lights on and bed and living lights off';
$output = preg_split( "/ (and) /", $input );
$num = (int)count($output);
$i=0;
while($i<$num){
if ((strpos($output[$i],'on') !== false)||(strpos($output[$i],'off')
!== false)) {}
elseif(((strpos($output[$i+1],'on') !==
false)||(strpos($output[$i+1],'off') !== false))){
$output[$i+1] .= ' + '.$output[$i];
unset($output[$i]);
}
$i++;
}
$output = array_values($output);
$i=0;
$num = (int)count($output);
echo '<br>';
while($i<$num){
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'on')
!== false)&&(strpos($output[$i],'kitchen') !== false)){
echo'kitchen lights on<br>';
}
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'off')
!== false)&&(strpos($output[$i],'kitchen') !== false)){
echo'kitchen lights off<br>';
}
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'on')
!== false)&&(strpos($output[$i],'living') !== false)){
echo'living lights on<br>';
}
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'off')
!== false)&&(strpos($output[$i],'living') !== false)){
echo'living lights off<br>';
}
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'on')
!== false)&&(strpos($output[$i],'bed') !== false)){
echo'bed lights on<br>';
}
if ((strpos($output[$i],'lights') !== false)&&(strpos($output[$i],'off')
!== false)&&(strpos($output[$i],'bed') !== false)){
echo'bed lights off<br>';
}
$i++;
}

No comments:

Post a Comment