From the topic itself, I need to compare a string to a line of text inside a textarea.
Here's the output i got from php from my linux server which i have program that prints for devices that are available and i put it inside a textarea.
Device -------------- | NAme ------------------- | Status
/dev/ttyS0-----------| Profilic |-------------------|Available
/dev/ttyUSB0 -------| Test | ---------------------|Busy
Now I have an array of devices..
$devices = array("/dev/ttyS0", "/dev/ttyUSB0", "/dev/ttyUSB1");
Now how can i compare my array of strings if the following devices in the textarea exist?
Say if /dev/ttyS0
found in the textarea then it returns true because i have /dev/ttyS0 in my array of strings.
Sample code how i get output from linux to php.
echo "<textarea>";
echo stream_get_contents($pipes[1]);
echo "</textarea>";
What i Want to happen.(mockup code)
if(/dev/ttyS0 == in the textarea){
enable this part of code
}
if(/dev/ttyUSB0 == in the textarea){
enable this part of code
}
and so on....
How can i do that?..
Assuming your device descriptors should appear at the start of a line in the textarea by your format above, you can iterate over the lines and look for strpos($line, $device) === 0
.
$lines = explode("\n", $teextarea_content);
// loop over array of device descriptors
// and make an array of those found in the textarea
$found_devices = array();
foreach ($devices as $device) {
// Iterate over lines in the textarea
foreach ($lines as $line) {
if (strpos($line, $device) === 0) {
// And add the device to your array if found, then break
// out of the inner loop
$found_devices[] = $device;
break;
}
}
}
// These are the devices you found...
var_dump($found_devices);
// Finally, enable your blocks.
if (in_array("/dev/ttyUSB0", $found_devices)) {
// enable for /dev/ttyUSB0
}
// do the same for your other devices as necessary
// OR... You could use a fancy switch in a loop to act on each of the found devices
// Useful if two or more of them require the same action.
foreach ($found_devices as $fd) {
switch($fd) {
case '/dev/ttyUSB0':
// stuff for this device
break;
case '/dev/ttyS0':
// stuff for this device
break;
// These two need the same action so use a fallthrough
case '/dev/ttyS1':
case '/dev/ttyS2':
// Stuff for these two...
break;
}
}
You will most likely want to use AJAX to do this... JQuery makes AJAX very simple.
but your PHP will want to look something along the lines of...
<?php
// Already assuming you have filled out your array with devices...
$dev = $_POST["device"];
// This will loop through all of your devices and check if one matched the input.
foreach($devices as $device) {
if ($device == $dev) {
// Whatever you want to do if the device matches.
}
}
?>
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.