2012-10-03 64 views
1

從題目本身相比,我需要一個字符串比較一個textarea裏面的文本行。一個字符串轉換爲文本行的文本區域內部在PHP

這裏的輸出我從PHP接到了,我有計劃,用於打印的可用設備我的Linux服務器,我把它放在一個文本里。

Device --------------  |  NAme  ------------------- |  Status 

/dev/ttyS0-----------| Profilic |-------------------|Available 

/dev/ttyUSB0 -------| Test | ---------------------|Busy 

現在我有設備陣列..

$devices = array("/dev/ttyS0", "/dev/ttyUSB0", "/dev/ttyUSB1"); 

現在,我怎麼比較我的字符串數組,如果存在於文本區域下面的設備?

說,如果在textarea的發現/dev/ttyS0然後,因爲我在字符串數組具有的/ dev/ttyS0來返回true。

示例代碼如何獲取輸出從Linux到PHP。

echo "<textarea>"; 
echo stream_get_contents($pipes[1]); 
echo "</textarea>"; 

我想發生。(樣機代碼)

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.... 

我該怎麼辦呢?..

回答

1

假設你的設備描述符應在textarea的行開始通過您的格式出現以上,您可以迭代線路並查找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; 
    } 
} 
+0

謝謝,但我怎麼知道它比較什麼字符串?例如/ dev/ttyS0或/ dev/ttUSB0?有沒有辦法讓我知道我比較正確的字符串,例如,我只想在文本行中找到/ dev/ttyS0? – demic0de

+1

@ demic0de以上將在textarea中查找原始數組中的所有設備,並將它在$ found_devices中找到的所有設備都存儲起來。如果你只想實際做某件事,那麼就像'in_array('/ dev/oneyouwanted',$ found_devices)''做一些事情。或者跳過整個過程,只要執行'preg_match('〜^/dev/ttyS0〜',$ line)'遍歷分解線。 –

+0

非常感謝,我又學到一些有用的東西.. – demic0de

0

您很可能希望使用AJAX做到這一點... JQuery使得AJAX非常簡單。

,但你的PHP會想看看沿線的東西...

<?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. 
    } 
} 
?> 

乾杯

+0

AJAX或JavaScript與此有什麼關係? –

+0

必須以某種身份提交信息。 AJAX請求只是讓事情看起來更加流暢。 –

+0

非常感謝,但我怎麼知道它比較什麼字符串?例如來自您的代碼。如果($ device == $ dev)找到了什麼設備?它是/ dev/ttyS0還是/ dev/ttyUSB0? – demic0de

相關問題