2010-06-09 27 views

Trả lời

39

Một phương pháp mà bạn có thể sử dụng trên các tập tin nhỏ hơn mà có thể phù hợp vào bộ nhớ của bạn hai lần:

$data = file('myfile'); // reads an array of lines 
function replace_a_line($data) { 
    if (stristr($data, 'certain word')) { 
    return "replaement line!\n"; 
    } 
    return $data; 
} 
$data = array_map('replace_a_line',$data); 
file_put_contents('myfile', implode('', $data)); 

Một lưu ý nhanh chóng, PHP> 5.3.0 hỗ trợ các hàm lambda để bạn có thể loại bỏ các tuyên bố hàm có tên và rút ngắn bản đồ để:

$data = array_map(function($data) { 
    return stristr($data,'certain word') ? "replacement line\n" : $data; 
}, $data); 

Bạn về mặt lý thuyết có thể làm điều này một đơn (khó khăn hơn để làm theo) php tuyên bố:

file_put_contents('myfile', implode('', 
    array_map(function($data) { 
    return stristr($data,'certain word') ? "replacement line\n" : $data; 
    }, file('myfile')) 
)); 

khác (ít bộ nhớ chuyên sâu) cách tiếp cận mà bạn nên sử dụng cho các tập tin lớn hơn:

$reading = fopen('myfile', 'r'); 
$writing = fopen('myfile.tmp', 'w'); 

$replaced = false; 

while (!feof($reading)) { 
    $line = fgets($reading); 
    if (stristr($line,'certain word')) { 
    $line = "replacement line!\n"; 
    $replaced = true; 
    } 
    fputs($writing, $line); 
} 
fclose($reading); fclose($writing); 
// might as well not overwrite the file if we didn't replace anything 
if ($replaced) 
{ 
    rename('myfile.tmp', 'myfile'); 
} else { 
    unlink('myfile.tmp'); 
} 
+0

Thanq ..... Đang hoạt động tốt – kishore

+0

Cách tiếp cận ít bộ nhớ là chính xác những gì tôi cần (đơn giản và dễ hiểu) ..... CẢM ƠN !!! – scottcarmich

5

Bạn cần phải ghi đè lên toàn bộ tập tin.

Vì vậy, đối với tệp tương đối nhỏ, read file into array, tìm kiếm từ, thay thế hàng được tìm thấy, viết all the rest vào file.

Đối với tệp lớn, thuật toán hơi khác, nhưng hoàn toàn giống nhau.

phần quan trọng là file locking

đó là lý do tại sao chúng tôi muốn có một cơ sở dữ liệu.

+0

+1 cho ghi chú trên 'flock()' – gnarf

2
$filedata = file('filename'); 
$newdata = array(); 
$lookfor = 'replaceme'; 
$newtext = 'withme'; 

foreach ($filedata as $filerow) { 
    if (strstr($filerow, $lookfor) !== false) 
    $filerow = $newtext; 
    $newdata[] = $filerow; 
} 

Bây giờ $newdata chứa các nội dung tập tin như là một mảng (sử dụng implode() nếu bạn không muốn mảng) với dòng có chứa "replaceme" thay bằng "withme".

3

Bạn cũng có thể sử dụng chế độ đa phù hợp với biểu thức thông thường

preg_match_all('/word}/m', $textfile, $matches); 

này là, tất nhiên, giả sử đó là một tài liệu nhỏ hơn ở tư thế sẵn sàng và tải. Nếu không, các câu trả lời khác là "thế giới thực" của giải pháp.

0

Có lẽ điều này có thể giúp:

$data = file("data.php"); 

for($i = 0;$i<count($data);$i++){ 
    echo "<form action='index.php' method='post'>"; 
    echo "<input type='text' value='$data[$i]' name='id[]'><br>"; 
} 

echo "<input type='submit' value='simpan'>"; 
echo "</form>"; 

if(isset($_POST['id'])){ 
    file_put_contents('data.php',implode("\n",$_POST['id'])) ; 
} 
1

này là tốt nếu bạn đang tìm kiếm một chuỗi con (ID) trong một dòng và muốn thay thế dòng cũ với một dòng mới.

Code:

$id = "123"; 
$new_line = "123,Programmer\r"; // We're not changing the ID, so ID 123 remains. 
$contents = file_get_contents($dir); 
$new_contents= ""; 
if(strpos($contents, $id) !== false) { // if file contains ID 
    $contents_array = preg_split("/\\r\\n|\\r|\\n/", $contents); 
    foreach ($contents_array as &$record) { // for each line 
     if (strpos($record, $id) !== false) { // if we have found the correct line 
      $new_contents .= $new_line; // change record to new record 
     }else{ 
      $new_contents .= $record . "\r"; 
     } 
    } 
    file_put_contents($dir, $new_contents); // save the records to the file 
    echo json_encode("Successfully updated record!"); 
} 
else{ 
    echo json_encode("failed - user ID ". $id ." doesn't exist!"); 
} 

Ví dụ:

Cũ file:

ID, nghề nghiệp

123, sinh viên

124, lớp gạch

Chạy mã sẽ thay đổi tập tin để:

New file:

ID, nghề nghiệp

123, lập trình viên

124, gạch lớp

Các vấn đề liên quan