当前位置: 动力学知识库 > 问答 > 编程问答 >

fopen - Writing some data to a specific area within a file in PHP

问题描述:

I'm experimenting with fopen for the first time and was wondering if it was possible to search for a particular section within a file before adding or replacing that content with data?

Ideally, I'd like to:

  1. Use fopen to get the file
  2. Search for a comment called <!-- test -->
  3. Replace that comment with new data.

This possible? (for the record - Appending data to the end of the file or adding new data to a specific line number would not work for what I'm working on as the file is constantly changing).

Thanks!

网友答案:

If you read the entire file in then use something str_replace to make the change, you should be able to get what you want.

网友答案:
<?php 
// make sure radio is set
if( isset($_POST['enableSocialIcons']) )
{
  // Open file for read and string modification 
  $file = "/test"; 
  $fh = fopen($file, 'r+'); 
  $contents = fread($fh, filesize($file)); 
  $new_contents = str_replace("hello world", "hello", $contents); 
  fclose($fh); 

  // Open file to write 
  $fh = fopen($file, 'r+'); 
  fwrite($fh, $new_contents); 
  fclose($fh); 
}
?> 

From: http://www.php.net/manual/en/function.fopen.php#81325

EDIT: To see what exactly is getting sent by your form do this at the top of the PHP file you're posting to:

<?php

echo '<pre>';
print_r($_POST);
echo '</pre>';

exit;

?>
分享给朋友:
您可能感兴趣的文章:
随机阅读: