2016-03-18 19 views
4

我對PHP有些新鮮感,但創建了幾乎所有我需要的東西,除了一件事導致我在這裏。我爲一個朋友創建了一個簡單的(對你來說可能但不是爲我)的網站,以便他們可以跟蹤他們何時收到租金付款,輸入新租戶並檢查當前餘額。我有一切工作完美...我想。在檢查天平時,我只用一個字輸入來測試以讀取文本文件並輸出適當的信息。但是,我發現如果第一個和最後一個名字之間存在一個空格,我沒有找到匹配。我需要使用代碼來讀取輸入的租戶名稱的整個空間。我還沒有找到任何我可以真正理解的東西,並且一直在尋找幾個晚上。這是我用於搜索和檢索結果的完整代碼。如何在文本文件中使用空格來匹配兩到三個單詞PHP

被搜索的文本文件是這樣的:

John Doe,123 Main St,400.00,01/01/2016, 
Jane Doe,124 Main St,300.00,01/01/2016, 
John Doe,123 Main St,,01/03/2016,200.00 
<?php 
$lines = file('data.txt'); //here's the filename 
?> 
<center> 
    <table id="historytable" width="640" border="1"> 
    <caption>Billing & Payment History 
</caption> 
<tbody> 
<tr> 
<td width="40">Tenant</td> 
<td width="40">Address</td> 
<td width="40">Date</td> 
<td width="40">Rent</td> 
<td width="40">Payment</td> 
</tr> 
<?php 
$search = $_POST["name"]; //assigning a string to each piece of input data 
// Store true when the text is found 
$balance = 0; //assign initial value to balance 
$renttotal = 0; //assign initial value to renttotals 
$received = 0; //assign initial value to received 
$found = false; 
foreach ($lines as $line) { //this is the loop to read the txt file 
{ 
    if(strpos($line, $search) !== false) 
    { 
    $found = true; 
list($a,$b,$c,$d,$e) = explode(',', $line); //this assigns a variable name to each data item separated by a comma 
    $renttotal+= $c; //each time it loops, it gathers the value of c adding it to itself same for the two lines below 
    $received+= $e; 
    $balance = $renttotal - $received; //subtracts the final value of renttotal and received assigning the difference to balance 

    $line_array = explode(",", $line); //breaks each piece of data apart to be placed in a table } 
    echo "<tr> 
<td width=40>$a</td> 
<td width=40>$b</td> 
<td width=40>$c</td> 
<td width=40>$d</td> 
<td width=40>$e</td> 
</tr>"; 
}}} 
?> 
</tbody> 
</table> 
</center> 
<BR /> 
<BR /> 
<center> 
    <p>TOTAL RENTS CHARGED $<?php echo "$renttotal"?><br /> 
    TOTAL PAYMENTS RECEIVED $<?php echo "$received"?><br /> 
    BALANCE DUE $<?php echo "$balance"?></p> 

預先感謝您的任何幫助。

+0

說實話,我似乎不瞭解你的問題。需要比較哪些字符串?另外,不要命名你的變量'a','b'等等,試着給它們更容易理解的名字,比如'$ name','$ address','$ amount'等。因此,你很可能會理解你的代碼在三個月內也是如此。 – Jan

+0

感謝您的回覆。這些變量僅僅是在我完美地調整編碼之前讓所有的東西都能正常工作。至於比較 - 用戶提交一個表格與租戶的全名到$ search = $ _POST [「name」];名稱。搜索data.txt文件中的所有實例的名稱(現在爲$ search)。當完全匹配時,它應該返回表中的全名,地址,租金,日期和付款。我希望我能正確解釋這一點。我想我可能在這裏有什麼問題 - if(strpos($ line,$ search)!== false)。再次感謝。 – SharonF

+0

如果「Jane」是輸入到$ search的輸入,編碼只會匹配正確,但如果它是「Jane Doe」,它將不匹配。 – SharonF

回答

0

簡單地做一個urldecode()像這樣:

$search = urldecode($_POST["name"]); 

而且你應該罰款之後。

+0

非常感謝你。我完美的工作! – SharonF

相關問題